通过隐式转换覆盖 Int 上的算术运算符 [英] Overriding arithmetic operators on Int via implicit conversions

查看:41
本文介绍了通过隐式转换覆盖 Int 上的算术运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say that, for aesthetical reasons, I want to be able to write:

3 / 4

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

and have / be a method on a class that there exists an implicit conversion from Int to, e.g.:

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

implicit def intToFoo(i: Int) = new Foo(i)

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

Is this at all possible, i.e. is it possible to "disable" the / method on Int?

推荐答案

简而言之:不,你不能.

In short: No, you can't.

只有在您尝试调用不存在的方法时才会进行隐式解析.

Implicit resolution will only take place if you attempt to call a method that doesn't already exist.

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

A more "idiomatic" solution would be to create your own pseudo-number type, something like:

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

val foo = Rational(3, 4)

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

val p = Path("3") / "4"

这篇关于通过隐式转换覆盖 Int 上的算术运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆