加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 使用私有构造函数参数扩展特征

发布时间:2020-12-16 18:36:57 所属栏目:安全 来源:网络整理
导读:在 Scala中,如何使用特征中定义的私有构造函数参数在类中扩展特征? trait Parent { protected def name: String require(name != "","wooo problem!")}class Child(private val name: String) extends Parent { println("name is " + name)} 上面的类给出了
在 Scala中,如何使用特征中定义的私有构造函数参数在类中扩展特征?

trait Parent {
  protected def name: String
  require(name != "","wooo problem!")
}

class Child(private val name: String) extends Parent {
  println("name is " + name)
}

上面的类给出了一个错误:

class Child needs to be abstract,since method name in trait Parent of type ? String is not defined.

当然,我可以:

>使Child类抽象化,
>在类似Child(val name:String)的构造函数中不使用private来定义它.
>使父类成为抽象类而不是特征

但是通过上面的实现,在扩展特性时我是否有办法获得私有构造函数参数?请注意,我希望变量是私有的,这样我就不能做childInstance.name.

解决方法

试试这个

trait Parent {
    protected def name: String
    require(name != "","wooo problem!")
  }

  class Child(override protected val name: String) extends Parent {
    val publicVar = "Hello World"
    println("name is " + name)
  }

  def main(args: Array[String]): Unit = {
    val child = new Child("John Doe")
    println(child.publicVar)
    println(child.name) // Does not compile
  }

您将无法访问child.name

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读