隐式接口
Coddy 面向 Go 开发者的 Dart 课程的第 34 课,共 48 课。
Go 接口通过结构实现:只要 Bell 具有 sound() string 方法,它就会成为 Sound,无需在任何地方声明。Dart 则把两方面都反过来。每个普通 Dart 类都会根据其实例成员定义一个隐式接口,因此类无需单独声明就能充当接口,但只有在通过 implements、extends 或 with 明确说明时,类才是子类型。Dart 的子类型关系是名义型的:仅仅具有匹配方法的类并不是 Sound。
每个普通 Dart 类都会根据其实例成员定义一个隐式接口。私有成员的名称以下划线开头,它们也是该接口的一部分,但只能在所属库内访问,这与未导出的 Go 名称只能在所属包内使用类似。implements 会建立名义契约,但不会继承实现代码。
完整的 Go 程序:
package main
import "fmt"
type Sound interface{ sound() string }
type Bell struct{}
func (Bell) sound() string { return "ding" }
func main() {
var s Sound = Bell{}
fmt.Println(s.sound())
}
完整的 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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 Dart中的所有课
自己练习: Dart 在线编译器