繁体   English   中英

Scala中的继承类型别名在构造函数声明中是不可见的,但在构造函数体中是可见的

[英]Inherited type alias in Scala is invisible in constructor declaration but visible in constructor body

为什么Scala表现得像这样?

更重要的是, 如何修复此代码

我问这个问题,因为我有一些复杂的类型,我需要在几个子类的构造函数声明中使用,我想保持DRY

class Parent{
  type IntAlias=Int
}

class Child (val i1:IntAlias=3) extends Parent{ //Compilation error, why ?
  val i2:IntAlias= 1  //No problem here!
}

编译错误:

 not found: type IntAlias
class Child (val i1:IntAlias=3) extends Parent{
                    ^

在您的定义中, IntAliasParent类的成员。 因此,如果没有Parent实例 ,则无法访问该成员。 您可以将第二种情况视为val i2: this.IntAlias = 1 在这里,您可以访问的实例this

对于值而不是类型,这类似于以下内容:

class Parent {
  def intValue: Int = 1234
}

class Child(val x: Int = intValue) extends Parent  // does not compile

因此,您必须将该成员放在不同的范围内,例如伴随对象:

 object Parent {
   type IntAlias = Int
 }
 import Parent.IntAlias

 class Child(val i1: IntAlias = 3) extends Parent {
   val i2: IntAlias = 1
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM