Effective Scala, part 1 - elements of a program
Collected in Effective Scala series
Table of contents
Value (or Data in this context)
A value is the representation of some entity that can be manipulated by a program.
Value is the most abstract definition here, but it is made concrete by subsequent definitions.
Literal
A literal is a text representation of a value in source code.
-
1is an integer literal -
"1"is a string literal -
(x) => x * xis a function literal aka anonymous function in JavaScript -
{id: 1, (x) => x * x}is an object literal in JavaScript, etc.
(Data) Type
A data type (or simply type) is a collection of data values.
A type is usually specified by a set of possible values, and a set of allowed operations on these values.
The members of a type are the values of that type.
Expression
An expression is a syntactic entity that can evaluate to a value.
An expression combines literals, constants, variables, and expressions, by applying operations (functions, operators, methods) on them.
-
1is an integer literal that is also a simple expression that evaluates to value1. Value1belongs to typeInteger. -
"Alice" + " Wonderland"is an expression that combines two string literals by applying the operation+on them. Literal"Alice"represents the valueAlice. The valueAlicebelongs to typeString. The operation+is an operator/method defined on typeStringand can be applied on literals, constants, variables that represent a value of typeString. -
("Alice" + " Wonderland").toUpperCaseis an expression in which operationtoUpperCaseis applied on the expression"Alice" + " Wonderland". The expression"Alice" + " Wonderland"evaluates to a valueAlice Wonderlandof typeString. The operationtoUpperCaseis a method defined on typeStringand can be applied on literals, constants, variables that represent a value of typeString.
Program
A program expresses a computation. (A computation is any type of arithmetic or non-arithmetic calculation that is well-defined).
A program is a sequence of expressions (and/or statements too, but let's keep it simple here).
-
1 + 1is an expression, but also a program which expresses the computation of adding 1 to 1.
Another perspective on Type
Types define the rules for combining expressions. The types define how the expressions can be combined, by applying operations to them. For this reason, operations are also called members of types.
For instance, the && operation (and) is available on the type Boolean, and it expects another Boolean value on its right-hand side. We say that the type Boolean has a member named && (and), which takes another Boolean value as a parameter.
If you try to apply an operation to an expression, whose type does not provide such an operation, it's an error.
Written by Jayesh Bhoot