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

m528fe3b  于 2022-11-23  发布在  Scala
关注(0)|答案(1)|浏览(136)

我有以下程序:

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

我尝试用一些逻辑创建构造函数。但是,由于
'Rational'不接受参数
有什么问题吗?

z2acfund

z2acfund1#

尝试引入帮助器方法

import scala.util.matching.Regex

def gcd(i: Int, i1: Int): Int = BigInt(i).gcd(BigInt(i1)).toInt

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) = {
    this(Rational.transformStr(s)._1, Rational.transformStr(s)._2)
  }
}

object Rational {
  // helper method
  def transformStr(s: String): (Int, Int) = {
    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)
      (num, 1)
    else
      (num, input(1).toInt)
  }
}

或者更好的工厂方法(因为构造函数有很多限制)

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
}

object Rational {
  // factory methods
  def apply(n: Int) = new Rational(n, 1)

  def apply(s: String): Rational = {
    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)
      new Rational(num, 1)
    else
      new Rational(num, input(1).toInt)
  }
}

Executing code in overloaded constructor prior to calling this()
顺便说一下,您也可以使用默认值

class Rational(n: Int, d: Int = 1 /*default*/ ) {
  // ...
}

object Rational {
  def apply(s: String): Rational = ???
}

相关问题