Previous << Scope
Next >> Type Inference(型推論)
Cadence プログラミング言語は型安全言語(type-safe language)です。
変数に新しい値を割り当てる場合、その値は変数と同じ型でなければなりません。例えば、変数がBool
型の場合、割り当てられる値はBool
型のみであり、例えばInt
型は不可です。
/* Declare a variable that has type `Bool`. */
var a = true
/* Invalid: cannot assign a value that has type `Int` to a variable which has type `Bool`. */
a = 0
関数に引数を渡す場合、値の型は関数のパラメータの型と一致していなければなりません。例えば、関数がBool
型の引数を期待している場合、Bool
型の値のみ渡すことができ、例えばInt
型の値は渡せません。
fun nand(_ a: Bool, _ b: Bool): Bool {
return !(a && b)
}
nand(false, false)
/* is `true` */
/* Invalid: The arguments of the function calls are integers and have type `Int`,
* but the function expects parameters booleans (type `Bool`).
*/
nand(0, 0)
型は自動的に変換されません。例えば、整数型は自動的にブーリアン型に変換されません。また、Int32
は自動的にInt8
に変換されません。また、オプショナルの整数型Int?
は自動的にオプショナルではない整数型Int
に変換されません。また、その逆も同じです。
fun add(_ a: Int8, _ b: Int8): Int8 {
return a + b
}
/* The arguments are not declared with a specific type, but they are inferred
to be `Int8` since the parameter types of the function `add` are `Int8`. */
add(1, 2)
/* is `3` */
/* Declare two constants which have type `Int32`. */
let a: Int32 = 3_000_000_000
let b: Int32 = 3_000_000_000
/* Invalid: cannot pass arguments which have type `Int32` to parameters which have type `Int8`. */
add(a, b)
翻訳元
Flow BlockchainのCadence version1.0ドキュメント (Type Safety)