Scala constructor with default arg argument, referencing another arg argument

I would make the second argument of the constructor optional and use the value of the first argument in this case. Is there any way to do this? This code does not compile since it cannot find realUser :

 class CurrentUser(val realUser:String, val masqueradeUser:String = realUser) 

I'm sure I can get around this by writing my own constructor, but I wondered if there was a more concise way. In fact, now that I have tried to write my own constructor, this is not so bad:

 class CurrentUser(val realUser:String, val masqueradeUser:String) { def this(realUser:String) = this(realUser, realUser) } 

If someone can come up with something shorter than great, otherwise I will send my own answer.

+8
constructor scala
source share
3 answers

Thanks for the suggestions. I think that I will specify the second form of the constructor manually. Here it is as an answer for completeness.

 class CurrentUser(val realUser:String, val masqueradeUser:String) { def this(realUser:String) = this(realUser, realUser) } 
+5
source share

I believe your solution with an auxiliary constructor is the best. The parameter does not appear in its own parameter list, only in the following. So you will need to do

 class CurrentUser(val realUser: String)(val masqueradeUser: String = realUser) 

and then call with

 new CurrentUser(real)() 

Not very nice.

+11
source share

You cannot use reuse options from the same parameter list as the default arguments. The didierds solution works, and probably your solution with the second constructor is the most elegant. Here's the third option, which uses the scary null :

 scala> class CurrentUser(val realUser:String, _masqueradeUser: String = null) { | val masqueradeUser = if (_masqueradeUser == null) realUser else _masqueradeUser | } defined class CurrentUser scala> new CurrentUser("paul").masqueradeUser res1: String = paul scala> new CurrentUser("paul", "p").masqueradeUser res2: String = p 

If you want to avoid null , you can use the Opt[A] class here if you don't mind the overhead. Somehow, Id still comes with his second constructor solution.

+8
source share

All Articles