Jayesh Bhoot's Ghost Town

Effective Scala, part 1 - elements of a program

Posted on in

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.

  • 1 is an integer literal
  • "1" is a string literal
  • (x) => x * x is 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.

  • 1 is an integer literal that is also a simple expression that evaluates to value 1. Value 1 belongs to type Integer.
  • "Alice" + " Wonderland" is an expression that combines two string literals by applying the operation + on them. Literal "Alice" represents the value Alice. The value Alice belongs to type String. The operation + is an operator/method defined on type String and can be applied on literals, constants, variables that represent a value of type String.
  • ("Alice" + " Wonderland").toUpperCase is an expression in which operation toUpperCase is applied on the expression "Alice" + " Wonderland". The expression "Alice" + " Wonderland" evaluates to a value Alice Wonderland of type String. The operation toUpperCase is a method defined on type String and can be applied on literals, constants, variables that represent a value of type String.

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 + 1 is 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.