Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking functions returned by methods that take implicits

Given the following function:

def foo()(implicit count: Int): (String => Seq[String]) = {
  s => for (i <- 1 until count) yield s
}

Calling apply() on the result explicitly works:

implicit val count = 5

val x = foo().apply("x") // <- works fine

And setting the result to a val, which you then call as a function, works:

val f: String => Seq[String] = foo()
f("y") // <- works fine

But trying to do it all in one line, without apply, confuses the compiler into thinking you're passing the implicit explicitly:

val z = foo()("z") // type mismatch; found: String("z"), required: Int

Is there a way to do this without either the explicit apply or the intermediate val? For instance, is it possible somehow to move the implicit declaration into the returned anonymous function?

like image 383
David Moles Avatar asked May 31 '26 09:05

David Moles


1 Answers

scala> (foo() _)("z")
res10: Seq[String] = Vector(z, z, z, z)
like image 62
Chris B Avatar answered Jun 03 '26 01:06

Chris B