If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Wednesday, July 24, 2013

Using self-type (Scala)

package types
object SelfTypeDemo {
/**
* using the self-type we declare that any BigTimeSpender also must be a Millionaire
*/
trait BigTimeSpender {
self: Millionaire =>
def wasteMoney: Unit = println("I can waste money on champagne")
}
trait Millionaire
//class RichEmployee extends BigTimeSpender
/**
* This does not compile and gives following error:
* illegal inheritance; self-type types.SelfTypeDemo.RichEmployee
* does not conform to types.SelfTypeDemo.BigTimeSpender's selftype
* types.SelfTypeDemo.BigTimeSpender with types.SelfTypeDemo.Millionaire
*/
//we have to mixin Millionaire
class RichEmployee extends BigTimeSpender with Millionaire
//but the order in which the traits are mixed in does not matter for this particular case
class OtherRichEmployee extends Millionaire with BigTimeSpender
def main(args: Array[String]): Unit = {
val employee1 = new RichEmployee
employee1.wasteMoney
val employee2 = new OtherRichEmployee
employee2.wasteMoney
//we can also create a similar type in runtime
val employee3 = new Object with BigTimeSpender with Millionaire
employee3.wasteMoney
}
}
view raw gistfile1.scala hosted with ❤ by GitHub

No comments:

Post a Comment