Barak BN
Barak BN

Reputation: 558

Supplying implicit argument EXPLICITLY

I have a function like this:

case class SomeCaseClass(i: Int)

def func[T: Manifest](someArg: Int)(implicit i: String) = {
  SomeCaseClass(2)
}

I need to call func and supply i explicitly

but when I call func[SomeCaseClass](2)("hello"), I get:

error: not enough arguments for method func: (implicit evidence$1: Manifest[ScalaFiddle.this.SomeCaseClass], implicit i: String)ScalaFiddle.this.SomeCaseClass. Unspecified value parameter i. funcSomeCaseClass("hello")

Any way to do it without changing the function's signature?

Upvotes: 0

Views: 469

Answers (2)

anuj saxena
anuj saxena

Reputation: 279

When I define the method func in my scala REPL, I am finding the output as:

func: [T](someArg: Int)(implicit evidence$1: Manifest[T], implicit i: String)SomeCaseClass

In other words, the same code can also be written as:

def func1[T](someArg: Int)(implicit manifest: Manifest[T], i: String) = {
  SomeCaseClass(2)
}

It is described here as well.

So in the above code, we can see that the implicit section now have two parameters, not the only String. And you need to provide all the params of the implicit section in case you want to fill them explicitly. If you're providing just one it will throw a compilation error.

Hence your method func can be called through the below code:

func(2)(Manifest.classType(classOf[SomeCaseClass]), "hello")

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170849

You need to give all implicit parameters explicitly if you give any, and T: Manifest means there is an additional implicit parameter.

Happily, implicitly method will summon the implicit which the compiler would have supplied:

func[SomeCaseClass](2)(implicitly, "hello") // inferred to implicitly[Manifest[SomeCaseClass]]

Upvotes: 3

Related Questions