Ben Kovitz
Ben Kovitz

Reputation: 5030

Trying to skip implicit parameter list

I'd like to call a function returned by a function with an implicit parameter, simply and elegantly. This doesn't work:

def resolveA(implicit a: A): String => String = { prefix =>
  s"$prefix a=$a"
}

case class A(n: Int)
implicit val a = A(1)

println(resolveA("-->"))  // won't compile

I've figured out what's going on: Scala sees the ("-->") and thinks it's an attempt to explicitly fill in the implicit parameter list. I want to pass that as the prefix argument, but Scala sees it as the a argument.

I've tried some alternatives, like putting an empty parameter list () before the implicit one, but so far I've always been stopped by the fact that Scala thinks the argument to the returned function is an attempt to fill in the implicit parameter list of resolveA.

What's a nice way to do what I'm trying to do here, even if it's not as nice as the syntax I tried above?

Upvotes: 2

Views: 314

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

Another option would be to use the apply method of the String => String function returned by resolveA. This way the compiler won't confuse the parameter lists, and is a little shorter than writing implicltly[A].

scala> resolveA[A].apply("-->")
res3: String = --> a=A(1)

Upvotes: 3

Related Questions