Interface polymorphism
This recipe declares a small interface, implements it explicitly, and calls a method through the interface value.
Project tree
text
polymorphism/
└── main.kmSource
ts
import go fmt from "fmt";
interface Greeter {
function greet(): string;
}
class Guest implements Greeter {
constructor(private name: string) {}
public function greet(): string {
return "Welcome, " + this.name;
}
}
function message(greeter: Greeter): string {
return greeter.greet();
}
function main(): void {
const guest = new Guest("Aki");
fmt.Println(message(guest));
}Run
sh
keika check main.km
keika run main.kmExpected output:
text
Welcome, AkiContract demonstrated
Guestexplicitly namesGreeterinimplements.- The compiler validates its public instance method signature.
- A
Guestclass value is a reference with identity. - Passing it as
Greeteruses generated Go interface dispatch. - The private
namefield is not exposed as a public Go field.
Interfaces are intentionally explicit even when a method set happens to match. Classes can also implement imported Go interfaces when their generated public method set satisfies the original Go contract.
See Classes and structs.