Skip to content

Duck Type

Eric Yang edited this page Jun 27, 2021 · 1 revision

鸭子类型

采用组合的方式组织程序

type Quack {
    quack: () -> ()
}

type Duck impl Quack {
    fun quack() -> {
        print("quaaaack");
    }
}

// no impl Quack
type Bird() impl {
    fun quack() -> () {
        print("bird quaaaack");
    }
}

fun sound(animal: Quack) -> () {
    animal.quack();
}
let duck: Duck = new Duck();
let bird: Bird = new Bird();

// type checking pass
sound(duck); // quaaaak
sound(bird); // bird quaaaak
Clone this wiki locally