Type Inference
Type inference means that the compiler automatically infers the type of a variable or an expression based on the program context, so that a developer does not need to explicitly write the type. As a modern programming language, Cangjie also supports type inference.
In Cangjie, the type of a variable can be inferred based on the type of the initialization expression. In addition to the inference of variable type, Cangjie also supports the inference of the return value type of a function. In Cangjie, the last expression of a function body is regarded as the return value of the function. When the return type is omitted in the function definition, it is inferred based on the return value.
var foo = 123 // foo is 'Int64'.
var bar = 'hello' // bar is 'String'.
func add(a: Int, b: Int) { // add returns Int.
a + b
}
Cangjie also supports the inference of type parameters in a generic function call, including the inference of generic parameters in the Currying function. The following is an example.
func map<T, R>(f: (T)->R): (Array<T>)->Array<R> {
...
}
map({ i => i.toString() })([1, 2, 3]) // Supports the inference of generic parameters in the Currying function.
// The inference result is map<Int, String>({ i => i.toString() })([1, 2, 3]).
Note that the parameter type (T
) and return value type (R
) of the lambda expression (the first parameter of map
) can be inferred, and the inference of the parameter type (T
) depends on the inference of the type (Array<T>
) of the second parameter of map
.