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]?
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 tof2(g => g map f).Let's see what we know so far:
f2(Try[T] => Try[S]):Unitf: T => Sf2(g => g map f)Give 1. and 3. we can infer that the type of
ghas to beTry[T]. map overTry[T]takesT => Something, in casefwhich isT => S, in which case Something isS.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):For bonus points use the
_as the first char in your implementation.