Can someone help me understand the following behavior?
Simply put: what is the difference between the following two cases where...
c
+ trait t
scala> class c {val x=true; val y=this.x} defined class c scala> trait t {} defined trait t
scala> new c with t res32: c with t = $anon$1@604f1a67
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!
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
In Java, a class can contain another class known as nested class. It's possible to create a nested class without giving any name. A nested class that doesn't have any name is known as an anonymous class. An anonymous class must be defined inside another class. Hence, it is also known as an anonymous inner class.
In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With