Skip to content
Kavachकवच

Interface Values

Also known as: interface value dynamic dispatch polymorphism trait object virtual heterogeneous list

● Intermediate4 minBefore this: InterfacesSpec 2.15

An interface is also a type for values: a [Describe] can hold users and rectangles together.

interface Describe {
    fn describe(self) -> String
}

type User: Describe {
    name: String

    fn describe(self) -> String { "User {self.name}" }
}

type Rect: Describe {
    width: Int
    height: Int

    fn describe(self) -> String { "Rect {self.width}x{self.height}" }
}

fn main() {
    const all: [Describe] = [User(name: "Ravi"), Rect(width: 1, height: 1), User(name: "Mira")]
    for d in all {
        print(d.describe())
    }
}

The program ran and printed:

kavach run interface-values.kav

User RaviRect 1x1User Mira
interface-values.kav: Kavach code, then what running it prints

Each d.describe() calls the method of whatever type d holds. Only the interface's methods can be used on such a value. To tell a closed set of types apart, use a union instead.