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…

Hello
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)
a.printX
42
a.x
^
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)

In the last example @curoli shows the x is available to the body of the class but is not exposed as an attribute. Constructor parameters are available to the body of the class but unless you mark them as val or var (but don’t do that :slight_smile: then they are not made visible except to the body of the class. Note that case classes automatically mark all construction parameters as val.

class A(x: Int) { def printX: Unit = println(x) }
class B(val x: Int) { def printX: Unit = println(x) }
case class C(x: Int) { def printX: Unit = println(x) }

Above A can printX but you cannot access x given an instance of A. With B you will be able to access x given an instance. C looks like A but acts like B because it is a case class which automatically provides the val on the construction parameters.