隐式接口
Coddy 面向 Luau 开发者的 Dart 课程的第 34 课,共 48 课。
Luau 表类型描述结构:只要某个表包含兼容的 sound 函数,就符合 Sound 类型,无需声明 implements。类型注解提供的是静态检查,而不是运行时接口对象。Dart 接口是名义类型的;即使某个无关的类具有匹配的方法,也需要声明子类型关系。
每个普通的 Dart 类都会根据其实例成员定义一个隐式接口。私有成员也属于该接口,但只能在其库内访问。implements 建立名义契约,但不会继承实现主体。
完整的 Luau 程序:
type Sound = {sound: () -> string}
local bell: Sound = {sound = function(): string return 'ding' end}
local function listen(value: Sound): string
return value.sound()
end
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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Luau 开发者的 Dart中的所有课
自己练习: Dart 在线编译器