user3139545 user3139545 - 2 years ago 134
Scala Question

implicits in scala Class constructors

I dont understand why only one out of the three examples below are working? What makes the other two faulty?

class H(implicit a:String, b: Int) {

class H(a:String, implicit b: Int) {

class H(implicit a:String, implicit b: Int) {

Answer Source

In the first case implicit doesn't refer to a but to the entire parameter list. It means "a and b can be provided implicitly when calling the constructor" (and also makes them available as implicits in the class body). You can't make a single parameter of a class or a method implicit in this sense.

The second use of implicit is to mark a type/object member. Constructor parameters aren't members, but can be made into members by using val/var, as in pamu's answer; or, to avoid making it visible, private[this] val.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download