Scala problem optional constructor

北战南征 提交于 2019-12-21 12:26:59

问题


Imagine this simple piece of code:

    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()
 }
}

The result is

null
null

I would like to be

calling elvis
null

How to achieve this? I cannot call the method testMethod after the object creation.

Mazi


回答1:


Your test method is called in the main constructor first thing. There is no way another constructor might avoid it being called before its own code runs.

In your case, you should simply reverse which constructor does what. Have the main constructor have the string parameter, and the auxiliary one set it to null. Added gain, you can declare the var directly in the parameter list.

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

In general, the main constructor should be the more flexible one, typically assigning each field from a parameter. Scala syntax makes doing exactly that very easy. You can make that main constructor private if need be.

Edit: still simpler with default parameter

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


来源:https://stackoverflow.com/questions/7203292/scala-problem-optional-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!