gpt4 book ai didi

Scala问题可选构造函数

转载 作者:行者123 更新时间:2023-12-04 09:42:39 25 4
gpt4 key购买 nike

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

    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。

麻子

最佳答案

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

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

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

一般来说,主构造函数应该是更灵活的构造函数,通常从参数中分配每个字段。 Scala 语法使得做这件事变得非常容易。如果需要,您可以将该主构造函数设为私有(private)。

编辑 :使用默认参数更简单
class Constructor(var s: String = null) {
def testMethod = println(s)
testMethod
}

关于Scala问题可选构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7203292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com