I am using scala 2.12 and IntelliJ IDE. I tried to auto-generate apply method in Scala companion object using readily available template. It generated apply method with fields having val because I have created class having fields declared as val in primary constructor.
Please refer below code snippet for mode details or check it here :
class Name(val firstName : String,val lastName : String)
object Name {
def apply(val firstName: String,val lastName: String): Name =
new Name(firstName,lastName)
}
I am getting compilation error : identifier expected but val found
Why Scala compiler generates error here while using var or val on fields of apply method ? What is the important concept behind this restriction ?
Because that's the way methods are defined in Scala, there is no need for a val
or var
in front of a method parameter. As Luis said, a method parameter is always immutable.
It should just be:
def apply(firstName: String, lastName: String) = ???
I'm a bit surprised but IntelliJ IDEA is fooling you on this one and generating wrong code.