soc*_*soc 5 types scala compiler-errors units-of-measurement implicit-conversion
考虑Scala中某些测量功能单元的简化片段:
object UnitsEx {
case class Quantity[M <: MInt, T: Numeric](value: T) {
private val num = implicitly[Numeric[T]]
def *[M2 <: MInt](m: Quantity[M2, T]) =
Quantity[M, T](num.times(value, m.value))
}
implicit def measure[T: Numeric](v: T): Quantity[_0, T] = Quantity[_0, T](v)
implicit def numericToQuantity[T: Numeric](v: T): QuantityConstructor[T] =
new QuantityConstructor[T](v)
class QuantityConstructor[T: Numeric](v: T) {
def m = Quantity[_1, T](v)
}
sealed trait MInt
final class _0 extends MInt
final class _1 extends MInt
}
Run Code Online (Sandbox Code Playgroud)
此代码段显示了我目前使用的用法和编译器错误:
import UnitsEx._
(1 m) * 1 // Works
1 * (1 m) // Doesn't work:
/*
<console>:1: error: overloaded method value * with alternatives:
(x: Double)Double <and>
(x: Float)Float <and>
(x: Long)Long <and>
(x: Int)Int <and>
(x: Char)Int <and>
(x: Short)Int <and>
(x: Byte)Int
cannot be applied to (UnitsEx.Quantity[UnitsEx._1,Int])
1 * (1 m)
^
*/
Run Code Online (Sandbox Code Playgroud)
包装1with measure将解决问题,但为什么不应用隐含的范围?
如果我删除类型参数,M就像在下一个片段中一样,它开始工作,虽然我看不到该类型参数如何与隐式搜索相关:
object UnitsEx2 {
case class Quantity[T: Numeric](value: T) {
private val num = implicitly[Numeric[T]]
def *(m: Quantity[T]) = Quantity[T](num.times(value, m.value))
}
implicit def measure[T: Numeric](v: T): Quantity[T] = Quantity[T](v)
implicit def numericToQuantity[T: Numeric](v: T): QuantityConstructor[T] =
new QuantityConstructor[T](v)
class QuantityConstructor[T: Numeric](v: T) {
def m = Quantity[T](v)
}
}
Run Code Online (Sandbox Code Playgroud)
这是预期的还是类型检查器的已知限制?