Skip to content

SpecificationIII · Types and values

3.2

Relations between types and widening

A value only moves by itself from one type to another when the target type contains it whole: from Integer to Real, from Character to String and from a subclass to its superclass.

Markdown version

3.2.1 How it works

Two types can be related in three different ways, and they should not be mixed up:

  • Equality: they are the same type.
  • Widening: a value of one fits into the other without losing anything.
  • Assignability: a value can be stored in a variable of the other, either because they are equal or because it widens.

There are three widenings, and no more:

Figure 3.2-1.The only three arrows the engine follows on its own. The crossed-out arrows require a conversion function.

Three green arrows: from Integer to Real, from Character to String and from a subclass to its superclass. Below, in red, the conversions that never happen by themselves: Real to Integer, Boolean to number and number to text.

Widening applies when initialising, assigning, passing an argument by value, returning a result and storing in a collection. Also when comparing: a character compared with a string is widened to a string before comparing.

ProgramAutomatic widenings

Algorithm Amplia
  Define r As Real <- 3;
  Define letra As Character <- 'a';
  Define texto As String <- letra;
  Write r, " ", texto, " ", letra = "a";
EndAlgorithm

Output

3.0 a true

The program finishes normally.

In the opposite direction there is no widening: a Real does not become an Integer by itself, a Boolean is not a number and a number does not turn into text by itself.

ProgramAn integer is not a text

Algorithm NoAmplia
  Define t As String <- 5;
EndAlgorithm

Diagnostics

  • incompatibleTypesInAssignment · error · 2:3 · Incompatible types in assignment: cannot assign integer to string

The program finishes with an error.

In short

  • Equality, widening and assignability are different relations.
  • There are only three widenings: Integer to Real, Character to String and subclass to superclass.
  • Everything else is requested with a conversion function.
  • By reference requires the exact type.