1

I compile the following code

def foo(implicit x: Int, x2: Int) = println(x2 + x) implicit val x : Int = 2 foo(1) 

But the compiler moans about the number of arguments. Why would the above work if there was only parameter x marked as implicit, but it does not work in this example?

3 Answers 3

4

You have to put the implicit argument is a separated, its own parenthesis:

scala> def foo(x2: Int)(implicit x: Int) = println(x2 + x) scala> implicit val x: Int 2 scala> foo(1) 3 

If you put non implicit argument and implicit argument in the same parenthesis, you have to explicitly pass both arguments otherwise compiler will complain about the wrong number of arguments. Scala compiler will try to look for implicit arguments when it sees that the argument is marked as implicit and no argument has been passed explicitly. But compiler checks if the right number of argument has been passed before checking for the implicit.

Sign up to request clarification or add additional context in comments.

Comments

2

This will work as you want:

def foo(x2: Int)(implicit x: Int) = println(x2 + x) implicit val x : Int = 2 foo(1) 

I'm not too deep into Scala internals and spec so I cannot give an in depth-explanation why this is, but you have to pass implicits with an extra set of parenthesis.

Edit: Because I was curious I had a look around the interwebs. I will not retype all the stuff I just found myself so you can find more detailed information here: http://daily-scala.blogspot.de/2010/04/implicit-parameters.html

Comments

2

Implicit parameters are all-or-nothing. Either you pass all of them explicitly, or you don't pass any of them and the compiler picks implicits for all.

In the example you should you are passing a parameter to foo, so you have to pass everything. If you had only one parameter in foo, it would work because the number of parameters is correct (and the parameter would be passed explicitly). If you call foo without passing any parameters, it will also work because it will pick implicit val x for both parameters.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.