user2051561 user2051561 - 11 days ago 6
Scala Question

Scala missing parameter type in type class operator

I have the following code:

class Pipe[ A ]( a: A ) {
def |>[ B ]( f: A => B ) = f( a )
def !>[ B ]( f: A => B ) : Try[B] = Try(f( a ))
def !>[ B, C ]( f: B => C )(implicit ev: A =:= Try[B]) : Try[C] = a.map(f)
}


(Implicit and apply not included)

I am having problems with the "missing parameter type" error.
The following code compiles correctly:

val r1 = 5 |> (x => x + 1)


However the following fails to compile:

val r6 = 100 !> { x => x * 2 }


Unless I write:

val r6 = 100 !> { x : Int => x * 2 }


So how do I get around the need to type the function?

I looked for answers on similar problems. One solution is to curry the function. However in this case I think the problem is type flowing
from type A of class Pip[A] to B when A =:= Try[B].

Appreciate any pointers.

TIA.

Answer

The only case in which you can omit an anonymous function's parameter type is when it is used in a context with an expected type, and this expected type is a function type (or, starting with Scala 2.12, a SAM type). Parameter for an overloaded method doesn't have an expected type, because its type needs to be known to choose the overload in the first place. So you need to give different names to the two !> methods.

Comments