Search code examples
scalascala-cats

Expect a function but a value is passed


I have following trait definition:

trait Printable[A] { self =>
  def format(value: A): String

  def show() : String = "Hello"

  def contramap[B](func: B => A): Printable[B] =
    new Printable[B] {
      def format(value: B): String =
        self.format(func(value))
    }
}

and a type:

final case class Box[A](value: A)

and the implicit implementation of it:

  implicit def boxPrintable[A](implicit p: Printable[A]) =
    p.contramap[Box[A]](_.value)  

contramap expects a function with func: B => A and a value is passing above. Why the compiler does not complain?


Solution

  • It's the underscore.

    Remember that _.value is shorthand for x => x.value which, in this case, means ...

    (x:Box[A]) => x.value
    

    ... which fits the definition of B => A where B is Box[A] and A is ... well, A. It's still unresolved, but the compiler has nothing to complain about because there is nothing contradictory in the code.