[英]infix operator with automatic number conversion
這個簡化的(有些人為的)示例與我要尋找的非常接近。
implicit class PlusMinus(a: Double) {
def +-(b: Double) = if (a > b) a-b else a+b
}
有了這個我可以:
scala> 3 +- 4L
res0: Double = 7.0
scala> 5f +- 1
res1: Double = 4.0
scala> 7L +- 6f
res3: Double = 1.0
但是我想知道:
每個結果都是Double。 我可以在標准庫中模仿自動數字轉換嗎?
Int +- Int = Int Long +- Long = Long Long +- Float = Float // etc.
有沒有更好的辦法? (總有更好的方法。)
您可以這樣實現您的運算符
implicit class PlusMinus[T](a: T)(implicit ev : Numeric[T]) {
def +-(b: T) = if (ev.gt(a, b)) ev.minus(a, b) else ev.plus(a , b)
}
這種快速解決方案有一個問題,只有兩個操作數中的類型相同才行。
這個似乎可以解決您的問題:
implicit class PlusMinus[T](a: T)(implicit ev : Numeric[T]) {
def +-(b: Double) = {
val ad = ev.toDouble(a)
if (ad > b) ad - b else ad + b
}
def +-(b: Long) = {
val ad = ev.toLong(a)
if (ad > b) ad - b else ad + b
}
def +-(b: Int) = {
val ad = ev.toInt(a)
if (ad > b) ad - b else ad + b
}
def +-(b: Float) = {
val ad = ev.toFloat(a)
if (ad > b) ad - b else ad + b
}
}
我們有結果
3 +- 4 //> res0: Int = 7
3 +- 4L //> res1: Long = 7
3L +- 4 //> res2: Int = 7
您可以在最后一個中看到,結果類型是第二個操作數的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.