ChapterÂ 2.Â Working with Data: Literals, Values, Variables, and Types
In this chapter we will cover the core data and variable types in Scala. Letâs start with the definitions of the terms literal, value, variable, and type:
- A literal (or literal data) is data that appears directly in the source code, like the number 5, the character A, and the text âHello, World.â
- A value is an immutable, typed storage unit. A value can be assigned data when it is defined, but can never be reassigned.
- A variable is a mutable, typed storage unit. A variable can be assigned data when it is defined and can also be reassigned data at any time.
- A type is the kind of data you are working with, a definition or classification of data. All data in Scala corresponds to a specific type, and all Scala types are defined as classes with methods that operate on the data.
The data stored in values and variables in Scala will get automatically deallocated by the Java Virtual Machineâs garbage collection when they are no longer used. There is no ability, or need, to deallocate them manually.
Letâs try exercising these terms by working with data in the Scala REPL. Scala values are defined with the syntax
val <name>: <type> = <literal>, so we will create a value with the name
Int (short for âintegerâ), and assigned it the literal number 5:
scala> val x: Int = 5 x: Int = 5
What happened here? The REPL (again, a Read-Evaluate-Print-Loop shell) read the value definition, evaluated it, and reprinted ...
Get Learning Scala now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.