Question

Suppose that I have the following scala code:

trait ValueSource[A] {
  def value(a: Int): A
}

trait ValueSourceOps[A] {
  def self: Int
  def F: ValueSource[A]
  def value: A = F.value(self)
}

trait ToValueSourceOps {
  implicit def toValueSourceOps[A](index: Int)(implicit F0: ValueSource[A]): ValueSourceOps[A] =    new ValueSourceOps[A] {
    def self = index
    def F: ValueSource[A] = F0
  }
}

object Test extends ToValueSourceOps {
  def value[A: ValueSource](index: Int): A = toValueSourceOps(index).value
}

The code above compiles well, but when I change the last line (body of method "value" in object Test) to

def value[A: ValueSource](index: Int): A = index.value

the compiler complains that could not find implicit value for parameter F0: ValueSource[A]

In my opinion, def value[A: ValueSource] means I have a implicit value "ValueSource[A]", then why does the compilation fail?

Was it helpful?

Solution

The A in toValueSourceOps has no relationship with the A in value, which makes inferring it problematic. To me the real question is why it works when you call the method explicitly.

I'm guessing that, when toValueSourceOp is called explicitly, it has to infer the same A because that's the only implicit available.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top