Initializing an anonymous class with a trait

Bosh picture Bosh · Aug 13, 2013 · Viewed 16.9k times · Source

Can someone help me understand the following behavior?

Simply put: what is the difference between the following two cases where...

I define a simple class c + trait t

scala> class c {val x=true; val y=this.x} 
defined class c

scala> trait t {}
defined trait t

I can instantiate a new "c with t"

scala> new c with t
res32: c with t = $anon$1@604f1a67

But I can't instantiate a new "[anonymous class just like c] with t"

scala> new {val x=true; val y=this.x} with t
<console>:9: error: type mismatch;
 found   : type
 required: ?{def x: ?}
<console>:9: error: value x is not a member of object $iw
              new {val x=true; val y=this.x} with t

What's the difference between these two cases?

Thanks!

Answer

Kristian Domagala picture Kristian Domagala · Aug 14, 2013

Is this what you're after:

new t {val x=true; val y=this.x}

If you have another trait, u {}, you can write new t with u {val x=true; val y=this.x}