0

How can I mark an argument to an anonymous n-ary function implicit? For example, consider the following:

def foo(f: (String, Int) => String): String = f("cat", 2)

def bar(s: String)(implicit i: Int): String = s * i

foo { implicit (s, i) =>
    bar(s)
}

The last line doesn't compile, reporting the following error:

test_tuple_implicits.scala:7: error: expected start of definition
foo { implicit (s, i) =>
               ^
one error found

This is strange to me because I know it's possible to mark an argument as an implicit for unary functions, such as when using Play web framework:

Action { implicit request =>
  Ok("Got request [" + request + "]")
}

I've also tried marking each value implicit foo { (implicit i, implicit s) => with no luck. Search engines have not been very helpful either, but I'm not sure I have the right keywords.

EDIT: It seems like I can make this work by editing the definitions like this:

def foo(f: String => Int => String): String = f("cat")(1)

def bar(s: String)(implicit i: Int) =  s * i

foo { s => implicit i => 
    bar(s)
}

I'm wondering if there is a cleaner solution though, and in particular a way to mark two values implicit at once (like implicit a, b).

Ceasar
  • 22,185
  • 15
  • 64
  • 83
  • Thanks. That looks related, but is not what I'm asking. – Ceasar Apr 19 '17 at 20:26
  • The first question you linked to is asking what `implicit` does when applied to an argument of an anonymous function. The second question has a similar title, but in the body it's seems to be asking how to define an anonymous function with an implicit parameter, where I'm asking how I can make an argument to an anonymous function implicit. – Ceasar Apr 19 '17 at 20:44
  • You have already found the supported solution, currying is the only way to achieve this. – Chris K Apr 19 '17 at 21:26
  • I've came close to what, I think, you want do using exactly what Play does. If you define your `foo` method to actually be the `apply` of a specific object, you can then construct it passing a Function literal. ```trait foo { self => final def apply(f: (String, Int) => String): String = f("cat", 2) } object foo extends foo ``` and then you use it this way ```foo { (a:String, b:Int) => b.toString }``` Unfortunately you can only define a single implicit parameter for a function literals. Hope I helped you somehow. – mfirry Apr 19 '17 at 21:31

0 Answers0