扩展方法
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 {
}