Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an anonymous class with a trait

Tags:

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!

like image 398
Bosh Avatar asked Aug 13 '13 21:08

Bosh


People also ask

When to use anonymous class?

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.

What is a anonymous class?

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.

What is anonymous class in Scala?

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.


1 Answers

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}

like image 103
Kristian Domagala Avatar answered Sep 20 '22 03:09

Kristian Domagala