1

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.

user2051561
  • 838
  • 1
  • 7
  • 21

1 Answers1

3

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • Understand now. I am using 2.12.0 and changed !> map to #>. If I assign variables to every use of #> (or use parenthesis) it works. However If I try and chain these it fails: `"Cannot prove that Double ⇒ Double =:= scala.util.Try[Double]. - not enough arguments for method #>: (implicit ev: =:=[Double ⇒ Double,scala.util.Try[Double]])scala.util.Try[Double]. Unspecified value parameter ev."` Can you tell me why? – user2051561 Nov 23 '16 at 18:09
  • 1
    It's clearly looking for wrong evidence, but hard to say why without seeing the actual code. You could try providing `#>` by an implicit class on `Try[A]` instead and avoid the `=:=`. – Alexey Romanov Nov 24 '16 at 06:45
  • I am going to set-up another question for. Meantime I will try the implicit class as you suggest. Appreciate the time you took to look at this. – user2051561 Nov 24 '16 at 11:22
  • For those interested, here is a back reference to this last issue: http://stackoverflow.com/questions/40788426/scala-operator-causes-compilation-error-but-not-why – user2051561 Nov 24 '16 at 14:07