Scala 这种别名和自类型 [英] Scala this aliasing and self type

查看:10
本文介绍了Scala 这种别名和自类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个别名self type之间有什么关系吗?这个别名self type的特例吗?在scala 2nd P776编程中,作者说:

Is there any relationship between this aliasing and self type? Is this aliasing a special case of self type? In programming in scala 2nd P776, the author said:

抽象类 Parser[+T] extends ... { p =>

abstract class Parser[+T] extends ... { p =>

你在 29.4 节看到过这样的语法,它被用来给出一个自我类型到特征.

You saw syntax like this in Section 29.4, where it was used to give a self type to a trait.

但是,self 类型的语法不是这样的,它是这样的:

but, the syntax for self type doesn't look like this, it's like:

this:SomeAssumedType =>

this:SomeAssumedType =>

另一个问题是为什么这个别名有用?我看不出给 this 引用一个别名有什么意义,因为它已经是当前对象引用的常规别名,但是在 Play 框架源代码中,我看到了很多代码(尤其是,anorm 部分)如:

And another question is why this aliasing is useful? I can't see there's any sense to give this reference an alias, because it's already a conventional alias for the current object reference, however in the Play framework source code, I saw lots of codes (especially, the anorm part) like:

trait RowParser[+A] extends (Row => SqlResult[A]) {

trait RowParser[+A] extends (Row => SqlResult[A]) {

父母 =>

为什么这有意义?

推荐答案

你可以同时拥有一个 self-type 和 this 别名:

You can have a self-type and this aliasing at the same time:

abstract class Parser[+T] { p: SomeAssumedType => … }

如果您不包含类型归属,Scala 将假定变量的类型是周围类的类型,从而为您提供 this 的简单别名.

If you don’t include a type ascription, Scala will assume that the type of the variable is the type of the surrounding class, thus giving you a simple alias for this.

如果您将名称 this 与归属保持在一起,那么 Scala 期望您以可以实现归属的方式初始化此类.

If you keep the name this with the ascription, then Scala expects you to initialise this class in a way that the ascription can be fulfilled.

至于 this 别名.以下是需要这样做的情况:

As for the this aliasing. Here’s the situation in which this is needed:

object OuterObject { outer =>
  val member = "outer"
  object InnerObject {
    val member = "inner"
    val ref1 = member
    val ref2 = this.member
    val ref3 = outer.member

    def method1 = {
      val member = "method"
      member
    }
    def method2 = {
      val member = "method"
      this.member
    }
    def method3 = {
      val member = "method"
      outer.member
    }
  }
}

scala> OuterObject.InnerObject.ref1
res1: java.lang.String = inner

scala> OuterObject.InnerObject.ref2
res2: java.lang.String = inner

scala> OuterObject.InnerObject.ref3
res3: java.lang.String = outer

scala> OuterObject.InnerObject.method1
res4: java.lang.String = method

scala> OuterObject.InnerObject.method2
res5: java.lang.String = inner

scala> OuterObject.InnerObject.method3
res6: java.lang.String = outer

这篇关于Scala 这种别名和自类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆