Types

Snap is a typed language.  This means data which you pass around (like variables, inputs to functions and subroutines, return values from functions, and blocks which give a value) all must specify a data type. An input expecting a certain data type must match the connected block's output data type.

Types can be either...

  • primitive, which means they represent elemental data such as numbers, booleans, and text.  A primitive example could be the height of an item, expressed as a number.
  • complex, meaning they are objects which contain properties which are of other complex types or primitives. A complex example could be a point in a three-dimensional space expressing height, width and depth.   This complex type we could call a "coordinate" and express it as three numbers.

Type Conversion

Sometimes the data you have is not in the type you need.  For example, you may have called out to a web service to get a value, and the web service returns a value as text, instead of as a number which you want.  If you attempt to use a math operation block on a text value "42" the block will be invalid. How can you solve this?

  • Casting.  In some cases, variables of one type can be easily converted to another type. This is called "casting".  We can cast the result of our web service – the text value of "42.5" – into a number value of 42.5. Note that while the two look similar to us, they are still of two distinct data types.  Even though the cast block will always try to cast a value from one type to another, this operation may not always give you a useful value.  Some values' data types are too different to cast in any useful way. For example, a value that is an array of text cannot be cast into a number.  In the case of converting an array to a number, the converted value will likely be 0 or null.
  • Text manipulation.  In many cases, you can extract just the characters you want from a string, and then cast that substring into a number.
  • Serialization.  If you have a complex object, you can easily convert it to a durable string for storage and future use by serializing it.

More on Types

Was this article helpful?