Skip to main content
Version: 1.0

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`.
_10
var a = true
_10
_10
// Invalid: cannot assign a value that has type `Int` to a variable which has type `Bool`.
_10
//
_10
a = 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.


_10
fun nand(_ a: Bool, _ b: Bool): Bool {
_10
return !(a && b)
_10
}
_10
_10
nand(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
//
_10
nand(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.


_16
fun 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`.
_16
add(1, 2) // is `3`
_16
_16
// Declare two constants which have type `Int32`.
_16
//
_16
let a: Int32 = 3_000_000_000
_16
let b: Int32 = 3_000_000_000
_16
_16
// Invalid: cannot pass arguments which have type `Int32` to parameters which have type `Int8`.
_16
//
_16
add(a, b)