Bundle state with methods. No inheritance; use interfaces for polymorphism. Use primary constructors to declare constructor parameters directly on the class:
class Counter(start: Int) {
mut count: Int = start
def increment(self) -> None {
self.count = self.count + 1
}
def get(self) -> Int {
return self.count
}
}
let c = Counter(10)
c.increment()
print(c.get()) # 11
Primary constructor parameters automatically become fields. Use init {} blocks for additional setup logic that runs after field initialization.
See Classes and data types for the full reference.
Immutable value objects. The compiler generates equals, hashCode, toString, and copy:
data Point {
x: Int
y: Int
}
let p1 = Point(1, 2)
print(p1) # Point(x=1, y=2)
print(p1 == Point(1, 2)) # True
let p2 = p1.copy(x=10) # Point(x=10, y=2)
Define method signatures that classes must implement:
interface Shape {
def area(self) -> Float {
}
}
class Circle(radius: Float) implements Shape {
mut radius: Float = radius
def area(self) -> Float {
return 3.14159 * self.radius * self.radius
}
}
A class can implement multiple interfaces: class X implements A, B { ... }.
A type with a fixed set of named variants. Variants can carry data:
enum Color {
RED
GREEN
BLUE
}
enum Shape {
Circle(radius: Float)
Rectangle(width: Float, height: Float)
Point
}
let c = Color.RED
let s = Shape.Circle(5.0)
Use match/case to destructure enum payloads:
match s {
case Shape.Circle(r) {
print(f"circle with radius {r}")
}
case Shape.Rectangle(w, h) {
print(f"{w}x{h} rectangle")
}
case Shape.Point {
print("point")
}
}
See Enums and pattern matching for the full reference.