Extension Overview
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
中文
1 modified sections0 code block delta0 anchor delta
modified扩展概述text+1 line, -1 line
v1.0.5
Section Text
1
扩展可以为在当前 `package` 中可见的类型(除函数、元组、接口)添加新功能。2
3
当不能破坏被扩展类型的封装性,但希望添加额外的功能时,可以使用扩展。4
5
可以添加的功能包括:6
7
- 添加成员函数8
- 添加操作符重载函数9
- 添加成员属性10
- 实现接口11
12
上述具体添加的功能方式可参考如下示例,具体使用语法请参考后续介绍:13
14
<!-- compile -->15
16
17
扩展虽然可以添加额外的功能,但不能变更被扩展类型的封装性,因此扩展不支持以下功能:18
19
1. 扩展不能增加成员变量。20
2. 扩展的函数和属性必须拥有实现。21
3. 扩展的函数和属性不能使用 `open`、`override`、 `redef`修饰。22
4. 扩展不能访问被扩展类型中 `private` 修饰的成员。23
24
根据扩展有没有实现新的接口,扩展可以分为 **直接扩展** 和 **接口扩展** 两种用法。直接扩展即不包含额外接口的扩展;接口扩展即包含接口的扩展,接口扩展可以用来为现有的类型添加新功能并实现接口,增强抽象灵活性。Code 1 · cangjie
1
interface Foo {2
func printValue(a: Int64): Unit3
}4
5
class Boo {6
var boo: Int64 =27
}8
9
extend Boo {10
public prop x: Int64 { // 添加成员属性11
get() {12
12313
}14
}15
16
func newMember(): Unit {17
println("This is a member function of a new extension.") // 添加成员函数18
}19
20
public operator func -() {21
println("Overload the operator addition function.") // 添加操作符重载函数22
-x23
}24
}25
26
// 接口扩展,实现接口27
extend<T> Array<T> <: Foo {28
public func printValue(a: Int64) {29
println("The is ${a}.")30
}31
}v1.1.0
Section Text
1
扩展可以为在当前 `package` 中可见的类型(除函数、元组、接口)添加新功能。2
3
当不能破坏被扩展类型的封装性,但希望添加额外的功能时,可以使用扩展。4
5
可以添加的功能包括:6
7
- 添加成员函数8
- 添加操作符重载函数9
- 添加成员属性10
- 实现接口11
12
上述具体添加的功能方式可参考如下示例,具体使用语法请参考后续介绍:13
14
<!-- compile -->15
16
17
扩展虽然可以添加额外的功能,但不能变更被扩展类型的封装性,因此扩展不支持以下功能:18
19
1. 扩展不能增加成员变量。20
2. 扩展的函数和属性必须拥有实现。21
3. 扩展的函数和属性不能使用 `open`、`override`、 `redef`修饰。22
4. 扩展不能访问被扩展类型中 `private` 修饰的成员。23
24
根据扩展有没有实现新的接口,扩展可以分为**直接扩展**和**接口扩展**两种用法。直接扩展即不包含额外接口的扩展;接口扩展即包含接口的扩展,接口扩展可以用来为现有的类型添加新功能并实现接口,增强抽象灵活性。Code 1 · cangjie
1
interface Foo {2
func printValue(a: Int64): Unit3
}4
5
class Boo {6
var boo: Int64 =27
}8
9
extend Boo {10
public prop x: Int64 { // 添加成员属性11
get() {12
12313
}14
}15
16
func newMember(): Unit {17
println("This is a member function of a new extension.") // 添加成员函数18
}19
20
public operator func -() {21
println("Overload the operator addition function.") // 添加操作符重载函数22
-x23
}24
}25
26
// 接口扩展,实现接口27
extend<T> Array<T> <: Foo {28
public func printValue(a: Int64) {29
println("The is ${a}.")30
}31
}