【问题标题】:Can't understand path dependent type无法理解路径依赖类型
【发布时间】:2017-07-10 06:01:12
【问题描述】:

对于一个 C 类,你可以在 body 中使用熟悉的 this 来引用当前实例,但 this 实际上是 Scala 中 C.this 的简写:

class C {
   var x = "1"
   def setX1(x:String) = this.x = x
   def setX2(x:String) = C.this.x = x
}

我只是无法理解C.this,C 是一个类,我无法理解为什么我们在Cthis 之间使用点,如C.this 所示?

【问题讨论】:

    标签: scala


    【解决方案1】:

    我不明白为什么我们在 C 和 this 之间使用点,如图所示 C.this

    this 之前使用类名在Java 中称为Qualified this(参见Using "this" with class name),在Scala 中类似。当您想从内部类引用外部类时使用它。例如,假设您在 C 类中有一个方法声明,您想在其中调用 this 并表示“C 的 this 引用:

    class C {
      val func = new Function0[Unit] {
        override def apply(): Unit = println(this.getClass) 
      }
    }
    
    new C().func()
    

    产量:

    class A$A150$A$A150$C$$anon$1
    

    您看到getClass 名称末尾的anon$1 了吗?这是因为在函数实例内部,这个this 实际上是函数类。但是,我们实际上想引用Cthis 类型。为此,您可以:

    class C {
      val func = new Function0[Unit] {
        override def apply(): Unit = println(C.this.getClass)
      }
    }
    
    new C().func()
    

    产量:

    class A$A152$A$A152$C
    

    注意末尾的C,而不是anon$1

    【讨论】:

      猜你喜欢
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      • 2019-06-06
      • 2013-04-17
      相关资源
      最近更新 更多