scala> :paste // Entering paste mode (ctrl-D to finish) trait Environment { val mode: String override val toString = "Running in mode '" + mode + "'" } // Exiting paste mode, now interpreting. defined trait Environment scala> val x = new Environment { override val mode = "production" } x: java.lang.Object with Environment = Running in mode 'null' //As you can see the mode is still null so instantiating Traits this way is a bad idea. //You can however use the construct below looking like an anonymous class definition scala> class Acceptance extends {val mode = "Acceptance"} with Environment defined class Acceptance scala> val y = new Acceptance y: Acceptance = Running in mode 'Acceptance' //or you can even skip constructing a class and just create a new Object directly scala> val dev = new {val mode = "Development"} with Environment dev: java.lang.Object with Environment = Running in mode 'Development'
Friday, June 15, 2012
Using early member definitions with Traits
Labels:
Scala
Subscribe to:
Post Comments (Atom)
Just for completeness, the following also works fine:
ReplyDeletetrait Environment {
def mode: String
override val toString = "Running in mode '" + mode + "'"
}
println(new Environment { def mode = "production" })
thanks for sharing, your articles are very helpful :)
ReplyDeleteBTW, I also have a blog and a web directory, would you like to exchange links? let me know on emily.kovacs14@gmail.com