What do we call those parameter types which are neither declared val nor var in Scala?


What do we call those parameter types which are neither declared val nor var in Scala?


Can you give an example?


I was wondering the same thing. Perhaps he is referring to the arguments of a case class constructor or the generated values to the left of the <- operator in for-comprehensions. I’d venture to guess that any parameter not declared as a var(iable) in scala is by default a val(ue). Did I guess right?


I think the only place where you can omit val or var is constructor parameters (that’s the name). If you omit them then compiler won’t generate accessors for them (hmm, not 100% sure) and also won’t emit a field for them if that field is not needed (roughly: if a constructor parameter is not used after construction then there’s no need for storing it in a field).


I agree with @tarsa – you’re probably talking about constructor parameters.

The key here (which isn’t obvious if you’re coming from other languages) is that class bodies in Scala are also, in a sense, functions; everything inside the class is essentially part of that function. So these parameters are just plain old function parameters, which get closed over inside of the body. They can be used inside the class body, but aren’t “members” in the class sense, and can’t be accessed from the outside…


I don’t think it can be done


The interesting case is code like this:

**Welcome to Scala 2.13.0 (OpenJDK 64-Bit Server VM, Java 1.8.0_212).
Type in expressions for evaluation. Or try :help.

class A(x: Int) { def printX: Unit = println(x) }
defined class A
val a = new A(42)
error: value x is not a member of A**

scala> a.getClass.getFields
res3: Array[java.lang.reflect.Field] = Array()

Somehow, the value of x must be stored, but how?


getFields only includes public fields.

scala 2.13.0> classOf[A].getFields
res2: Array[java.lang.reflect.Field] = Array()

scala 2.13.0> classOf[A].getDeclaredFields
res3: Array[java.lang.reflect.Field] = Array(private final int A.x)