3

I want IMPLICIT args in a higher order function, like:

func(arg1) { implicit (x, y) => x * y }

But the compiler says:

error: expected start of definition val a = func("2", "4") { implicit (x, y) => ^

  • java version "1.7.0_40"
  • Scala code runner version 2.10.2-RC2 -- Copyright 2002-2013, LAMP/EPFL

The runnable sample code:

object Test extends App {
    new Test().run
}

class Test {
    def run = {
        val a = func("2", "4") { (x, y) => // It's OK
            x * y
        }
        println("a: " + a)

        val b = gunc("2", "4") { implicit x => { implicit y => // It's OK
            x * y
        }}
        println("b: " + b)
    }

    def func(x: String, y: String)(f: (Int, Int) => Int) = f(x.toInt, y.toInt)
    def gunc(x: String, y: String)(g: Int => Int => Int) = g(x.toInt)(y.toInt)
    def hunc(x: String, y: String)(h: Tuple2[Int, Int] => Int) = h((x.toInt, y.toInt))
}

[ADD COMMENT]

I wonder...

We can declare as "implicit x => ..." with one arg.

It seems there is no way to declare two implicit args.

J Camphor
  • 303
  • 1
  • 7
  • It obviously won't fix a problem, but why don't you update to **final** version of Scala, e.g. 2.10.2 or 2.10.3? – om-nom-nom Oct 22 '13 at 13:24
  • no reason => I update 2.10.2. 'obviously' means what? Scala Prog Lang Spec mentions this problem? – J Camphor Oct 22 '13 at 17:40
  • I said *obviously* because the way parser works (your issue is language syntax) isn't something that usually changes between release candidate and final versions. So, upgrading to a stable version won't fix this problem, but will bring you overall stability instead. – om-nom-nom Oct 22 '13 at 18:08

2 Answers2

1

Try adding:

val c = hunc("2", "4") { implicit pair => pair._1 * pair._2 }
Shadowlands
  • 14,994
  • 4
  • 45
  • 43
1

When you say implicit y => y * 2 you're not declaring an implicit argument but mark the function as implicit, so you make an analog to this:

implicit val f1 = (y: Int) => y * 2
def func1(x: String, y: String)(f: Int => Int) = f(1)
func1("", "")(f1)

When you want to mark a function with two arguments as implicit you can do it this way:

implicit val f2 = (x: Int, y: Int) => y * 2
def func2(x: String, y: String)(f: (Int, Int) => Int) = f(1, 2)
func2("", "")(f2)

But you cannot do it so: func2("", "")(implicit (x, y) => x), in this particular case I just don't see any meaning to use implicits.

Also you can see this question, maybe you'll find some useful information there

Community
  • 1
  • 1
Eddie Jamsession
  • 1,006
  • 6
  • 24