implicits in scala Class constructors
Asked Answered
C

2

1

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) {
  //Working
}

class H(a:String, implicit b: Int) {
  //Not-Working
}

class H(implicit a:String, implicit b: Int) {
  //Not-Working
}
Charie answered 8/9, 2016 at 12:3 Comment(0)
A
3

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.

Acquittance answered 8/9, 2016 at 12:23 Comment(0)
I
1
class H1(implicit a:String, b: Int) {
  //Working
}

Need val or var in below two cases

class H2(a:String, implicit val b: Int) {
  //Working
}

class H3(implicit a:String, implicit val b: Int) {
  //Working
}
Involution answered 8/9, 2016 at 12:9 Comment(2)
class H2(a:String, implicit val b: Int) will compile but actually won't be an implicitLobectomy
@Łukasz It will declare b implicit inside the class though. Even more interesting happens with H3 where both a and b become implicit internally and externally, and constructor changes to new H3()("123", 456). Dark corners, you never know what lurks there.Hyperventilation

© 2022 - 2024 — McMap. All rights reserved.