通过隐式转换覆盖Int上的算术运算符

Knu*_*daa 4 scala

说,出于美学原因,我希望能够写:

3 / 4
Run Code Online (Sandbox Code Playgroud)

并且/是一个类的方法,存在从Int到的隐式转换,例如:

class Foo(val i: Int) {
  def /(that: Int) = // something
}

implicit def intToFoo(i: Int) = new Foo(i)
Run Code Online (Sandbox Code Playgroud)

这是否可能,即是否可以"禁用"Int上的/方法?

Kev*_*ght 7

简而言之:不,你不能.

只有在尝试调用尚不存在的方法时,才会发生隐式解析.

更"惯用"的解决方案是创建自己的伪数字类型,如:

case class Rational(a: Int, b: Int) {
  // other methods
}

val foo = Rational(3, 4)
Run Code Online (Sandbox Code Playgroud)

要么

case class Path(value: String) {
  def /(other: String): Path = ...
}

val p = Path("3") / "4"
Run Code Online (Sandbox Code Playgroud)