扩展方法
kotlin中是支持扩展方法的,Dart的实现和kotlin类似,但语法稍有不同
// 需要满足 extension on 类名 的格式
extension on String{
// 扩展方法名
String addDart(){
// 扩展的实现
return this+" Dart";
}
}
void main(){
// 调用扩展方法
var dart = 'hello'.addDart();
print(dart);
}
Mixin
不管是对于java还是kotlin的开发者Mixin都是一个新的概念,从效果上来说Mixin实现了代码的复用。看下代码:
// 不能有构造函数
mixin Draw {
int color = 16;
void draw() {
print("draw a picture");
}
}
// 复用Draw中的属性和方法
class Circle with Draw {}
void main() {
// 错误:mixin不能初始化
// var draw = Draw();
var circle = Circle();
// 调用Draw中的方法
circle.draw();
// 调用Draw中的属性
circle.color;
}
此外 可以使用关键字 on 来指定哪些类可以使用该 Mixin 类
class Shape{}
// 只能在Shape的子类中使用
mixin Draw on Shape{
int color = 16;
void draw() {
print("draw a picture");
}
}
class Circle extends Shape with Draw {
}
本文介绍了Dart语言中的扩展方法和Mixin特性。扩展方法允许为现有类添加新功能,而不需要继承或修改原始类。Mixin则提供了一种在多个类间重用代码的方式,通过with关键字将Mixin应用到类定义中。
2097

被折叠的 条评论
为什么被折叠?



