Deletions are marked like this. | Additions are marked like this. |
Line 6: | Line 6: |
* | * クラスの機能を分割する。 |
Line 33: | Line 33: |
== クラスの機能を分割する == {{{ trait SomeOther { def something } trait SomeOtherImpl extends SomeOther { def something = { println("something") } } class Sample { self: SomeOther => def test = { something } } object SelfTypeAnnotationSample2 { def main(args: Array[String]) { object SampleImpl extends Sample with SomeOtherImpl; SampleImpl.test } } }}} |
自分型アノテーション
自分型アノテーションの用途は二つある。
- thisの別名を定義する。
- クラスの機能を分割する。
thisの別名を定義する
object SelfTypeAnnotationSample1 { self => // 自分型アノテーション。=>の右側には何もない。「class Internal」を指しているわけでもない。 class Internal { def procedure = { SelfTypeAnnotationSample1.this.procedure self.procedure } } def procedure = { println("hello world") } def main(args: Array[String]) { new Internal().procedure } }
この結果は
hello world hello world
クラスの機能を分割する
trait SomeOther { def something } trait SomeOtherImpl extends SomeOther { def something = { println("something") } } class Sample { self: SomeOther => def test = { something } } object SelfTypeAnnotationSample2 { def main(args: Array[String]) { object SampleImpl extends Sample with SomeOtherImpl; SampleImpl.test } }