5

考慮的測量功能,一些單位的這個簡單的代碼片段在斯卡拉:爲什麼隱式搜索會受到無關類型參數的影響?

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 
} 

此片段展示了使用和編譯器錯誤,我得到目前:

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) 
^ 
*/ 

中包裝1measure將修復問題,但爲什麼不適用範圍的隱含?

如果我在未來的片斷就開始工作,雖然我不能看到類型參數是如何與隱性搜索中刪除類型參數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) 
    } 
} 

這個預期或已知的限制類型檢查器?

+0

還未完全解答的類似問題:http://stackoverflow.com/questions/7649517/why-is-the-implicit-conversion-not-considered-in-this-case-with-generic-paramete/ 7650605#7650605 – 2012-02-05 16:48:22

+0

哎喲...我完全忘記了我問過這個問題。 : -/ – soc 2012-02-05 20:09:18

+0

這仍然是一個很好的問題。 – 2012-02-05 23:24:58

回答

1

如果您將*運算符重命名爲例如mult然後1 mult (1 m)適用於這兩種情況。 這並不回答你的問題,但暗示方向可能會有一些干擾過重的運營商。

相關問題