Search code examples
scalascala-placeholder-syntax

Use of underscore in function call with Try parameters


I'm trying to understand particular use of underscore in Scala. And following piece of code I cannot understand

class Test[T, S] {
  def f1(f: T => S): Unit = f2(_ map f)

  def f2(f: Try[T] => Try[S]): Unit = {}
}

How is the _ treated in this case? How is the T=>S becomes Try[T]=>Try[S]?


Solution

  • It seems you are reading it wrongly. Look at the type of f2(Try[T] => Try[S]):Unit.

    Then looking into f1 we have f: T => S.

    The _ in value position desugars to f2(g => g map f).

    Let's see what we know so far:

    1. f2(Try[T] => Try[S]):Unit
    2. f: T => S
    3. f2(g => g map f)

    Give 1. and 3. we can infer that the type of g has to be Try[T]. map over Try[T] takes T => Something, in case f which is T => S, in which case Something is S.

    It may seem a bit hard to read now, but once you learn to distinguish between type and value position readin this type of code becomes trivial.

    Another thing to notice def f2(f: Try[T] => Try[S]): Unit = {} is quite uninteresting and may be a bit detrimental in solving your particular question.

    I'd try to solve this like that: first forget the class you created. Now implement this (replace the ??? with a useful implementation):

    object P1 { 
      def fmap[A, B](A => B): Try[A] => Try[B] = ??? 
    }
    

    For bonus points use the _ as the first char in your implementation.