Scalar Variables

Scalar variables are the most basic type of FPP. They are internally represented as float (single precision) or double precision decimal values. There are four types of scalar variables:

  1. Floating-point value: includes decimal number variables.
  2. Date: date in the form "YYYY-MM-DD". Dates are internally represented as number of days since 1970-01-01. A date can be created directly from its string representation, i.e. 1985-09-18.
  3. String: collection of multiple chars inside quotation marks. Strings are internally represented as an id from a dictionary and cannot have a date-like value (i.e. a string with value "2014-01-01" cannot be created due to type ambiguity).
  4. Boolean: variable with only two possible values, true or false. Booleans are internally represented as a float with value 0.0 or 1.0. A boolean can be created directly from true or false keywords.

The variable type is inferred from the assigned value, so you don’t need to explicitly declare the type of a scalar variable. A variable is declared with the def keyword. An example illustrating how each type of variable is declared and initialized is provided in the code block below:

def a = 15.25 // This is a floating-point value

def d = "2010-10-10" // This is a date

def b = "This is a string" // This is a string

def c = true // This is a boolean

However, being a type inferred language, you will get an error if you try to assign a wrong type value to a variable. For example, the code below will throw a Wrong type error:

def a = true
def b = "2010-01-01"
if (a == b) // will throw Wrong type: LocalDate, expected: boolean for 'b'
    return 42