Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Friday, June 15, 2012

Using early member definitions with Traits


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'

2 comments:

  1. Just for completeness, the following also works fine:

    trait Environment {
    def mode: String
    override val toString = "Running in mode '" + mode + "'"
    }

    println(new Environment { def mode = "production" })

    ReplyDelete
  2. thanks for sharing, your articles are very helpful :)
    BTW, I also have a blog and a web directory, would you like to exchange links? let me know on emily.kovacs14@gmail.com

    ReplyDelete