隐式接口
Coddy 面向 Python 开发者的 Dart 课程的第 34 课,共 48 课。
Python 通常依赖鸭子类型或静态 Protocol 检查。Dart 类接口是名义类型的:声明 implements 会建立子类型关系。仅仅拥有同名方法是不够的。
每个普通 Dart 类都会根据其实例成员定义一个隐式接口。私有成员属于该接口,但只能在其库内部访问。implements 会建立名义契约,但不会继承实现代码。
完整的 Python 程序:
class Bell:
def sound(self): return 'ding'
def listen(value): return value.sound()
print(listen(Bell()))
完整的 Dart 程序:
abstract class Sound{String sound();}
class Bell implements Sound{String sound()=>'ding';}
void main(){Sound s=Bell();print(s.sound());}挑战
简单实现抽象类 Scorer,其中包含 int score(String text)。LengthScore implements Scorer 返回字符串的 ASCII 长度。VowelScore implements Scorer 只统计小写字母 a、e、i、o、u。functions.dart 中的 best(List<String> words,Scorer scorer) 返回得分最高的第一个单词;如果列表为空,则返回 null。输入以 length 或 vowels 开头,后面是 ASCII 单词。输出得分最高的单词,或 none。
不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立测试公共 API,并在结果后打印一个换行符。
你的代码写在 Scorer.dart、LengthScore.dart、VowelScore.dart、functions.dart 和 exercise.dart 中。main.dart 包含提供的输入/输出代码,不能编辑。
亲手试试
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Scorer.dart';
import 'LengthScore.dart';
import 'VowelScore.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(LengthScore().score('abc')==3 && VowelScore().score('area')==3);check(best(['x','aaa'],LengthScore())=='aaa');
stdout.writeln(solve(input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 Dart中的所有课
自己练习: Dart 在线编译器