想象一下这段简单的代码:
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()
}
}
Run Code Online (Sandbox Code Playgroud)
结果是
null
null
Run Code Online (Sandbox Code Playgroud)
我想成为
calling elvis
null
Run Code Online (Sandbox Code Playgroud)
怎么做到这一点?在创建对象后我无法调用方法testMethod.
麻子
我有以下程序:
class Rational(n: Int, d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val numer = n / g
val denom = d / g
def this(n: Int) = this(n, 1)
def this(s: String) = {
val regex: Regex = "^([+-]?(\\d+|\\d*\\.?\\d+)|\\d*\\/?\\d+)$".r
if (!regex.matches(s)) throw new NumberFormatException()
val input: Array[String] = s.split("\\.|\\/")
val num: Int = input(0).toInt
if (input.length equals 1)
this(num, 1) // problem here
else
this(num, input(1).toInt) // problem here
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试用一些逻辑创建构造函数。但是,我不能因为
“Rational”不带参数
有什么问题?