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

Scala问题可选构造函数

发布时间:2020-12-16 08:49:48 所属栏目:安全 来源:网络整理
导读:想象一下这段简单的代码: class Constructor() { var string: String = _ def this(s: String) = {this() ; string = s;} def testMethod() { println(string) } testMethod}object Appl { def main(args: Array[String]): Unit = { var constructor = new
想象一下这段简单的代码:

class Constructor() {
  var string: String = _

  def this(s: String) = {this() ; string = s;}

  def testMethod() {
    println(string)
  }

  testMethod
}

object Appl {
  def main(args: Array[String]): Unit = {
    var constructor = new Constructor("calling elvis")
    constructor = new Constructor()
 }
}

结果是

null
null

我想成为

calling elvis
null

怎么做到这一点?在创建对象后我无法调用方法testMethod.

麻子

解决方法

首先在主构造函数中调用您的测试方法.在自己的代码运行之前,其他构造函数无法避免被调用.

在你的情况下,你应该简单地反转哪个构造函数做什么.让主构造函数具有字符串参数,辅助函数将其设置为null.添加了增益,您可以直接在参数列表中声明var.

class Constructor(var s: String) {
  def this() = this(null)
  def testMethod() = println(s)   
  testMethod()
}

通常,主构造函数应该是更灵活的构造函数,通常从参数中分配每个字段. Scala语法使得完成非常简单.如果需要,您可以将主构造函数设为私有.

编辑:使用默认参数仍然更简单

class Constructor(var s: String = null) {
   def testMethod = println(s)
   testMethod
}

(编辑:李大同)

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

    推荐文章
      热点阅读