Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala outer => syntax [duplicate]

Tags:

scala

Possible Duplicate:
What does “outer =>” really mean?

where I can find the information on

trait After extends Context { outer => xxx
//...
}

What does it mean outer =>?

like image 608
Stas Avatar asked Jul 26 '12 09:07

Stas


1 Answers

This is a self type. You can also add a type annotation, to force the class, that extends your trait to be of a certain type. But without a type it is just a reference to this (and is called a self-reference), so you can use it in inner classes etc. E.g.:

class MyOuter { outer =>
  // this == outer
  class MyInner {
    // this != outer
    def creator = outer
  }
}

The other usage I mentioned can for example be used to add special behaviour to existing classes:

class MyClass {
  val foo = "foo"
}

trait MyClassExtension { this: MyClass =>
  def fooExtended(s: String) = foo + s
}

scala> val x = new MyClass with MyClassExtension
x: MyClass with MyClassExtension = $anon$1@5243618

scala> x.fooExtended("bar")
res3: java.lang.String = foobar

Here the this: MyClass => means, that MyClassExtension can only be mixed into an instance or subclass of MyClass.

scala> class OtherClass
defined class OtherClass

scala> val x = new OtherClass with MyClassExtension
<console>:11: error: illegal inheritance;
 self-type OtherClass with MyClassExtension does not conform to MyClassExtension's selftype MyClassExtension with MyClass
       val x = new OtherClass with MyClassExtension
like image 101
drexin Avatar answered Sep 28 '22 16:09

drexin