小编Gri*_*rev的帖子

无法在 Scala 程序中创建带有逻辑的构造函数?

我有以下程序:

 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”不带参数

有什么问题?

constructor scala

0
推荐指数
1
解决办法
81
查看次数

标签 统计

constructor ×1

scala ×1