【问题标题】:Scala problem optional constructorScala问题可选构造函数
【发布时间】:2011-08-26 19:39:39
【问题描述】:

想象一下这段简单的代码:

    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 方法。

麻子

【问题讨论】:

    标签: scala constructor


    【解决方案1】:

    首先在主构造函数中调用您的测试方法。另一个构造函数无法避免在自己的代码运行之前调用它。

    在您的情况下,您应该简单地反转哪个构造函数做什么。让主构造函数具有字符串参数,辅助构造函数将其设置为空。增加了增益,可以直接在参数列表中声明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
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2019-10-02
      • 1970-01-01
      • 2019-05-22
      相关资源
      最近更新 更多