Scala traits

Really love scala,
traits and the ability of define custom types as interfaces.


type ObjectWithName = {
    def getName: String
}

trait NicePerson[T <: ObjectWithName] {
    def greet: String = {
        "Hello ! My name is %s".format(this.asInstanceOf[ObjectWithName].getName)
    }
}

class Person(name: String) {
    def getName: String = name
}

val peter = new Person("Peter") with NicePerson[Person]
println(peter.greet) // = Hello ! My name is Peter


How nice it is ?

Some references:
http://markthomas.info/blog/?p=92
http://codemonkeyism.com/scala-goodness-structural-typing/

Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: