J Camphor
J Camphor

Reputation: 303

How to declare implicit arguments in higher order functions?

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) => ^

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.

Upvotes: 3

Views: 1001

Answers (2)

Eddie Jamsession
Eddie Jamsession

Reputation: 1006

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

Upvotes: 1

Shadowlands
Shadowlands

Reputation: 15074

Try adding:

val c = hunc("2", "4") { implicit pair => pair._1 * pair._2 }

Upvotes: 1

Related Questions