Function Types
Inspect one language lane at a time so line-level text and code deltas stay readable.
Diff Lane
English
0 modified sections0 code block delta0 anchor delta
Diff Lane
中文
2 modified sections0 code block delta0 anchor delta
modified函数类型的类型参数text+1 line, -1 line
v1.0.5
Section Text
1
可以为函数类型标记显式的类型参数名,下面例子中的 `name` 和 `price` 就是 `类型参数名`。2
3
<!-- run -->4
5
6
另外对于一个函数类型,只允许统一写类型参数名,或者统一不写类型参数名,不能交替存在。7
8
<!-- compile.error -->Code 1 · cangjie
1
func showFruitPrice(name: String, price: Int64) {2
println("fruit: ${name} price: ${price} yuan")3
}4
5
main() {6
let fruitPriceHandler: (name: String, price: Int64) -> Unit7
fruitPriceHandler = showFruitPrice8
fruitPriceHandler("banana", 10)9
}Code 2 · cangjie
1
let handler: (name: String, Int64) -> Int64 // Errorv1.1.0
Section Text
1
可以为函数类型标记显式的类型参数名,下面例子中的 `name` 和 `price` 就是类型参数名。2
3
<!-- run -->4
5
6
另外对于一个函数类型,只允许统一写类型参数名,或者统一不写类型参数名,不能交替存在。7
8
<!-- compile.error -->Code 1 · cangjie
1
func showFruitPrice(name: String, price: Int64) {2
println("fruit: ${name} price: ${price} yuan")3
}4
5
main() {6
let fruitPriceHandler: (name: String, price: Int64) -> Unit7
fruitPriceHandler = showFruitPrice8
fruitPriceHandler("banana", 10)9
}Code 2 · cangjie
1
let handler: (name: String, Int64) -> Int64 // Errormodified函数类型作为变量类型text+1 line, -1 line
v1.0.5
Section Text
1
函数名本身也是表达式,它的类型为对应的函数类型。2
3
<!-- compile -->4
5
6
上述示例中,函数名是 `add`,其类型为 `(Int64, Int64) -> Int64`。变量 `f` 的类型与 `add` 类型相同,`add` 被用来初始化 `f`。7
8
若一个函数在当前作用域中被重载(见[函数重载](./function_overloading.md))了,那么直接使用该函数名作为表达式可能产生歧义,如果产生歧义编译器会报错,例如:9
10
<!-- compile.error -->Code 1 · cangjie
1
func add(p1: Int64, p2: Int64): Int64 {2
p1 + p23
}4
5
let f: (Int64, Int64) -> Int64 = addCode 2 · cangjie
1
func add(i: Int64, j: Int64) {2
i + j3
}4
5
func add(i: Float64, j: Float64) {6
i + j7
}8
9
main() {10
var f = add // Error, ambiguous function 'add'11
var plus: (Int64, Int64) -> Int64 = add // OK12
}v1.1.0
Section Text
1
函数名本身也是表达式,它的类型为对应的函数类型。2
3
<!-- compile -->4
5
6
上述示例中,函数名是 `add`,其类型为 `(Int64, Int64) -> Int64`。变量 `f` 的类型与 `add` 类型相同,`add` 被用来初始化 `f`。7
8
若一个函数在当前作用域中被重载(参见[函数重载](./function_overloading.md)),那么直接使用该函数名作为表达式可能产生歧义,如果产生歧义编译器会报错,例如:9
10
<!-- compile.error -->Code 1 · cangjie
1
func add(p1: Int64, p2: Int64): Int64 {2
p1 + p23
}4
5
let f: (Int64, Int64) -> Int64 = addCode 2 · cangjie
1
func add(i: Int64, j: Int64) {2
i + j3
}4
5
func add(i: Float64, j: Float64) {6
i + j7
}8
9
main() {10
var f = add // Error, ambiguous function 'add'11
var plus: (Int64, Int64) -> Int64 = add // OK12
}