Search code examples
scalascala-cats

Why it is possible to write currying?


I have the following code:

object ContraCats {

  val showString = Show[String]

  def main(args: Array[String]): Unit = {

    val m = showString.contramap[Symbol](_.name).show('dave)
    val a = showString.contramap[Symbol](_.name)('dave)

  }
}

As you can see, it is possible to write as currying version and the other as method call. Why it is possible?


Solution

  • The contramap returns a Show instance.

    Show has both the show and the apply methods.

    The apply method is special in Scala, since this two are equivalent:

    someValue.apply(someArg)
    someValue(someArg)
    

    So in your example what's happening is that you're calling the apply method on the Show instance returned by contramap, i.e.

    val m = showString.contramap[Symbol](_.name).show('dave)
    val a = showString.contramap[Symbol](_.name).apply('dave)
    

    Update

    While the explanation above would make sense, I realized cats's Show doesn't have an apply method, so your code shouldn't compile (I tried on a REPL and it doesn't)