scala self =>自身类型简单介绍

在使用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)
  }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值