Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is implicit search impacted by an unrelated type parameter?

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?

like image 966
soc Avatar asked Nov 13 '22 10:11

soc


1 Answers

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.

like image 150
Jan van der Vorst Avatar answered Dec 19 '22 04:12

Jan van der Vorst