plsdontbeangry
plsdontbeangry

Reputation: 55

Are variables objects in Scala?

Since Scala is a pure object oriented language, how are variables then objects themselves? I can see the literal value being an object itself in Scala, but not sure about the variables.

Upvotes: 0

Views: 229

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369614

Variables are not objects in Scala. This is not unique to Scala, it is true for all mainstream programming languages, even languages like Haskell or Smalltalk, and it is in fact true for almost all programming languages in general.

Every value is an object in Scala, but variables are not values, and thus are not objects. There are other things which are not values, most notably types. Types, classes, traits, and also methods.

objects sometimes look like they are both values and types, but actually, they are not. If you define an object Foo, then Foo is a value, but the type is the singleton type Foo.type, not Foo itself. For companion modules, you indeed have both a type named Foo, and a value named Foo, but those are different things. (Values and types can have the same name precisely because they are strictly separate, and thus there is never any possible confusion which of the two you are talking about.)

Literal types also look like you are using values as types, but actually, that is simply syntactic sugar. The literal type 42 is actually just syntactic sugar for the singleton type 42.type. Again, this works because values and types are two separate universes, and so there is never any context where it is unclear whether we are talking about the value or the literal type.

Another thing that isn't an object is the language syntax.

The only two languages I know about where variables are indeed objects that you can talk about and manipulate, are Ioke and Seph.

Upvotes: 6

Related Questions