-1

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 ?

Gunjan Shah
  • 5,088
  • 16
  • 53
  • 72
  • 3
    The arguments of a method are always immutable references. So using `val` would have been redundant and using `var` would not make sense, as such this is just invalid syntax. - In any case, that code is equivalent to just `final case class Name(firsName: String, lastName: String)` – Luis Miguel Mejía Suárez Jun 18 '21 at 14:48

1 Answers1

4

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.

Gaël J
  • 11,274
  • 4
  • 17
  • 32