Scala:你能用不止一个单行构造函数重载一个构造函数吗?
Scala: Can you overload a constructor with more than just a one-line constructor?
有没有一种方法可以使构造函数重载而不仅仅是一个单行构造函数?似乎在重载的构造函数中放置任何一个以上的语句都会给出错误 Application does not take parameters
。例如,如果主构造函数采用 String
,则以下将起作用:
def this(num: Int) = {
this(num.toString())
}
但是,以下不会:
def this(num: Int) = {
val numAsString = num.toString()
this(numAsString)
}
您可以改写如下:
def this(num: Int) =
this{
val numAsString = num.toString
numAsString
}
有没有一种方法可以使构造函数重载而不仅仅是一个单行构造函数?似乎在重载的构造函数中放置任何一个以上的语句都会给出错误 Application does not take parameters
。例如,如果主构造函数采用 String
,则以下将起作用:
def this(num: Int) = {
this(num.toString())
}
但是,以下不会:
def this(num: Int) = {
val numAsString = num.toString()
this(numAsString)
}
您可以改写如下:
def this(num: Int) =
this{
val numAsString = num.toString
numAsString
}