Search code examples
scalaimplicit

Why implicit parameter not working when combined with non implicit parameter


A very simple use case, let's say I have a class Foo that is accepting 2 parameters 1 is normal parameter and 1 is implicit.

class Foo(val msg: String, implicit val n: Int) {
  def multiplier = msg * n
}

implicit val num: Int = 4
val foo = new Foo("yo")
println(foo.msg)

I know it will work if I move the implicit parameter another list i.e. curried class Foo(val msg: String)(implicit val n: Int). But lets say for some reason I don't want to do that.

Can someone explain why the current version of implementation is not working?


Solution

  • Language specification is written this way. You have to define in a separate parameter list. Language specification is not speaking about implicit parameters at all, only about an implicit parameter list:

    Scala spec:

    An implicit parameter list (implicit p1,…,pn) of a method marks the parameters p1,…,pn as implicit. A method or constructor can have only one implicit parameter list, and it must be the last parameter list given.

    It might be possible to check if there is some reason in mailing list archives or other places.