5

Consider this simplified snippet of some units of measurement functionality in 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
}

This snippet shows the usage and the compiler error I get currently:

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

Wrapping the 1 with measure would fix the problem, but why isn't the implicit in scope applied?

If I remove the type parameter M like in the next snippet it starts working, although I can't see how that type parameter is related to implicit search:

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)
  }
}

Is this expected or a known limitation of the type checker?

soc
  • 27,983
  • 20
  • 111
  • 215
  • A similar question that was not fully answered: http://stackoverflow.com/questions/7649517/why-is-the-implicit-conversion-not-considered-in-this-case-with-generic-paramete/7650605#7650605 – Kipton Barros Feb 05 '12 at 16:48
  • Ouch ... I totally forgot I asked that question. :-/ – soc Feb 05 '12 at 20:09

1 Answers1

1

If you rename the * operator to e.g. mult then 1 mult (1 m) works in both cases. This does not answer your question but does hint in the direction that perhaps there is some interference with the heavily overloaded * operator.