Reputation: 73
I have a trait definition:
trait T {
def name: String
}
I can create an object like:
val o = new {
val name: String = "anonymous"
} with T
But I cannot create the object in the following way:
val o = new {
def name: String = "anonymous"
} with T
The compiler said ';' or newline expected in line } with T
. The only different is I used def
instead of val
in the second implementation.
I know that method can be defined in an anonymous object, but why I cannot use in this way here?
Upvotes: 1
Views: 3528
Reputation: 1978
The curly brackets in your two examples are "early definitions", explained here:
In Scala, what is an "early initializer"?
So it's initialization code, and not something that gets mixed in to your object.
The idea was raised on the Scala JIRA, and closed as "not a bug", here:
https://issues.scala-lang.org/browse/SI-912
Upvotes: 3