암시적 인터페이스
Coddy의 Go 개발자를 위한 Dart 코스 레슨. 48개 중 34번째.
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 컴파일러