title: Java or Scala: creating new types at runtime
body: <p>How do I define new types at runtime? I have a factory method that needs to create a new instance of <code>this.type</code> <strong>with a marker interface</strong>. The marker interface was not mixed in at compile time. I need to find a way to do this <strong>at runtime</strong>.</p>
  
  <p>I am using Scala, but I think the answer will be general enough to cover both Java and Scala.</p>
  
  <pre><code>trait Fruit {
      def eat: this.type with Eaten = {
          getClass.getConstructors()(0).newInstance(Array()).asInstanceOf[this.type]; 
          // somehow this needs to return a new instance of this.type with the Eaten trait
          // note that "Apple with Eaten" is not a type that exists at compile-time
      }
  }
  
  trait Eaten // marker interface
  
  class Apple extends Fruit
  
  val apple1 = new Apple
  val apple2 = a.eat // should return a new Apple with Eaten instance
  
  def eater(eaten: Eaten) = ... // this function only accepts Eaten fruit
  
  eater(apple1) // wont compile!
  eater(apple2) // will compile!
  </code></pre>