Scala问题可选构造函数 [英] Scala problem optional constructor

查看:110
本文介绍了Scala问题可选构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

结果是

null
null

我想成为

calling elvis
null

如何实现?我无法在对象创建后调用方法testMethod。

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

Mazi

推荐答案

p>你的测试方法是在主构造函数中调用的第一件事。没有其他构造函数可以避免它在自己的代码运行之前被调用。

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.

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

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

通常,主构造函数应该是更灵活的,通常从参数分配每个字段。 Scala语法使得这样做非常容易。如果需要,你可以使主构造函数私有。

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
}

这篇关于Scala问题可选构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆