Type Safety
The Cadence programming language is a type-safe language.
When assigning a new value to a variable, the value must be the same type as the variable.
For example, if a variable has type Bool
,
it can only be assigned a value that has type Bool
,
and not for example a value that has type Int
.
_10// Declare a variable that has type `Bool`._10var a = true_10_10// Invalid: cannot assign a value that has type `Int` to a variable which has type `Bool`._10//_10a = 0
When passing arguments to a function,
the types of the values must match the function parameters' types.
For example, if a function expects an argument that has type Bool
,
only a value that has type Bool
can be provided,
and not for example a value which has type Int
.
_10fun nand(_ a: Bool, _ b: Bool): Bool {_10 return !(a && b)_10}_10_10nand(false, false) // is `true`_10_10// Invalid: The arguments of the function calls are integers and have type `Int`,_10// but the function expects parameters booleans (type `Bool`)._10//_10nand(0, 0)
Types are not automatically converted.
For example, an integer is not automatically converted to a boolean,
nor is an Int32
automatically converted to an Int8
,
nor is an optional integer Int?
automatically converted to a non-optional integer Int
,
or vice-versa.
_16fun add(_ a: Int8, _ b: Int8): Int8 {_16 return a + b_16}_16_16// The arguments are not declared with a specific type, but they are inferred_16// to be `Int8` since the parameter types of the function `add` are `Int8`._16add(1, 2) // is `3`_16_16// Declare two constants which have type `Int32`._16//_16let a: Int32 = 3_000_000_000_16let b: Int32 = 3_000_000_000_16_16// Invalid: cannot pass arguments which have type `Int32` to parameters which have type `Int8`._16//_16add(a, b)