【问题标题】:Inherited type alias in Scala is invisible in constructor declaration but visible in constructor bodyScala 中的继承类型别名在构造函数声明中不可见,但在构造函数主体中可见
【发布时间】:2014-03-14 14:27:15
【问题描述】:

为什么 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{
                    ^

【问题讨论】:

    标签: scala type-alias


    【解决方案1】:

    在您的定义中,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
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      • 2011-08-28
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      • 2014-10-21
      相关资源
      最近更新 更多