Kevin Meredith
Kevin Meredith

Reputation: 41899

Invoking Function with Implicit and Non-implicit

I'm trying to define, what I think to be a "default argument", with an implicit argument:

scala> def f(implicit x: Int, y: String) = y
f: (implicit x: Int, implicit y: String)String

Note - I tried to define implicit x: Int as the second argument, but I got a compile-time error:

scala> def f(y: String, implicit x: Int) = y
<console>:1: error: identifier expected but 'implicit' found.
       def f(y: String, implicit x: Int) = y

Anyway, I define an implicit Int.

scala> implicit val x: Int = 100
x: Int = 100

Then I failed to invoke f with just a String argument:

scala> f("foo")
<console>:10: error: not enough arguments for method f: 
       (implicit x: Int, implicit y: String)String.
Unspecified value parameter y.
              f("foo")
               ^

Next, I tried to invoke the f function by specifying the argument. That failed too.

scala> f(y = "foo")
<console>:10: error: not enough arguments for method f: 
         (implicit x: Int, implicit y: String)String.
Unspecified value parameter x.
              f(y = "foo")
               ^

Is it possible to invoke the function f by providing an implicit and providing only a single argument for y?

Upvotes: 2

Views: 132

Answers (1)

Travis Brown
Travis Brown

Reputation: 139028

Implicit parameter sections are all or nothing—either you explicitly pass every argument (assuming they don't have default values) or none of them. You need to do something like this if you want f("foo") to work:

def f(y: String)(implicit x: Int) = y

I'd be careful about this approach, though—I'm personally increasingly inclined to think that using implicits for anything except type class instances is a bad idea, and having an implicit Int value floating around is kind of scary.

Upvotes: 3

Related Questions