在使用scala编程或者看一些scala语言写的框架时,经常会遇到一个类似如下的用法:
trait Printable[A] { self =>
def format(value: A): String
def contramap[B](func: B => A): Printable[B] =
new Printable[B] {
def format(value: B): String =
self.format(func(value))
}
}
此处的用法,有些类似于this别名,但又不完全一样。
其实它是scala自身类型用法的一种,这里我们来简单介绍一下自身类型
这个概念。
先来看一下scala官方的介绍:
“Aself type of a trait is the assumed type of this, the receiver, to be used within thetrait. Any
concrete class that mixesin the trait must ensure thatits type conforms to the trait’ s self type. The most common use of self types is for dividing a large classinto several traits"
具体来说,任何混入该特质的具体类必须确保它的类型符合特质的自身类型,自身类型最
通常的应用是将大类分成若干特质。
大类拆分的例子如下:
trait trait1 {
val hello = "Hello "
val world = "world"
def sayHello(): Unit = {
println(hello + world)
}
}
现在我们使用自身类型将其拆为为两个:
trait context {
val contextValue = "Hello world"
}
trait trait2 {
this: context =>
val hello = "Hello "
def sayHello(): Unit = {
println(hello + contextValue)
println(this.hello + this.contextValue)
}
}
除了拆分大类之外,自身类型还可以用于定义别名。
class A {
self =>
val num = 2
def foo = self.num + this.num
}
class A2 {
self: A2 =>
val num = 2
def foo = self.num + this.num
}
此处的self可以是任意名称。
同时,这个self在涉及内部类的地方同样有广泛使用:
class OuterClass {
outer =>
val outerStr = "here"
class InnerClass {
println(outer.outerStr)
}
}