学习 Scala3 扩展和 CanEqual 概念,但发现难以扩展 Int 的某些特性。
在以下示例中,我可以轻松地将 >= 功能添加到 Int 以将其与 RationalNumber 案例类进行比较,但无法修改 == 的行为。(注 1~2 与 RationalNumber(1,2) 相同)。
这个问题似乎与基本的 AnyVal 类型以及 Scala 如何传递给 Java 来处理 equals 和 == 有关。
case class RationalNumber(val n: Int, val d: Int):
def >=(that:RationalNumber) = this.num * that.den >= that.num * this.den
//... other comparisons hidden (note not using Ordered for clarity)
private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
val sign = if (n<0 ^ d<0) -1 else 1
private val (an, ad) = (math.abs(n), math.abs(d))
val num = sign * (an / gcd(an, ad))
val den = if(an == 0) 1 else ad / gcd(an, ad)
override def equals (that: Any): Boolean =
that match
case t: RationalNumber => t.den == den && t.canEqual(this) && t.num == num
case t: Int => equals(RationalNumber(t,1))
case _ => false
override lazy val toString = s"$num/$den"
object RationalNumber:
def apply (r: Int): RationalNumber = new RationalNumber(r, 1)
import scala.language.implicitConversions
implicit def intToRat (i: Int): RationalNumber = i ~ 1
given CanEqual[RationalNumber, Int] = CanEqual.derived
given CanEqual[Int, RationalNumber] = CanEqual.derived
extension (i: Int)
def ~(that: Int) = new RationalNumber(i, that)
def >=(that: RationalNumber) = i ~ 1 >= that
def equals (that: AnyVal) : Boolean =
println("this never runs")
that match
case t: RationalNumber => t.den == 1 && t.num == i
case _ => i == that
def ==(that: RationalNumber) =
println ("this never runs")
i~1 == that
object Main:
@main def run =
import RationalNumber._
val one = 1 ~ 1
val a = 1 == one // never runs extension ==
val b = one == 1
val c = 1 >= one
val d = one >= 1
val ans = (a,b,c,d) // (false, true, true, true)
println(ans)