Classes and interfaces
Classes hold data and behavior together, and can change over time. For values that never change, a data type is often simpler.
#Classes
A class's constructor parameters come after its name. Parameters marked let or var become properties:
class Counter(let name: String, var count: Int) {
fn increment() {
count += 1
}
fn report(): String = "{name}: {count}"
}
let clicks = Counter("clicks", 0)
clicks.increment()
clicks.increment()
println(clicks.report())
println(clicks.count)clicks: 2 2
Objects are made by calling the class like a function: Counter("clicks", 0). There is no new.
#Properties
Properties can also be declared in the body. let properties can't change after the object is made; var ones can:
class Account(let owner: String, opening: Int) {
var balance = opening
let history = mutableListOf<Int>()
fn deposit(amount: Int) {
balance += amount
history.add(amount)
}
}
let account = Account("Ada", 100)
account.deposit(50)
account.deposit(25)
println("{account.owner} has {account.balance}, after {account.history}")Ada has 175, after [50, 25]
A constructor parameter without let or var (like opening above) is only visible while the object is set up: in property values, init blocks and the superclass call.
#Init blocks
init { } runs when an object is made, after the properties above it are set:
class Temperature(let celsius: Float) {
init {
if celsius < -273.15 {
panic("colder than absolute zero")
}
}
fn fahrenheit(): Float = celsius * 9.0 / 5.0 + 32.0
}
println(Temperature(21.0).fahrenheit())69.8
#This
Inside a class, its members can be used without this.. Use this when a local name hides a member, or to pass the object along:
class Node(let value: Int) {
var next: Node? = null
fn append(value: Int): Node {
let node = Node(value)
this.next = node
return node
}
}
let head = Node(1)
head.append(2).append(3)
println(head.next?.next?.value)3
#Printing and equality
Objects print their properties, unless the class has its own toString(). == on objects compares identity: whether both sides are the same object.
class Point(let x: Int, let y: Int)
class Money(let cents: Int) {
fn toString(): String = "{cents / 100}.{cents % 100} euros"
}
let p = Point(1, 2)
println(p)
println(p == p)
println(p == Point(1, 2))
println(Money(1250))Point(x=1, y=2) true false 12.50 euros
#Inheritance
Classes are final unless declared open. A class extends one superclass, calling its constructor:
open class Animal(let name: String) {
open fn sound(): String = "..."
fn introduce(): String = "{name} says {sound()}"
}
class Dog(name: String) : Animal(name) {
override fn sound(): String = "woof"
}
class Puppy(name: String) : Animal(name) {
override fn sound(): String = "yip"
}
let animals: List<Animal> = [Dog("Rex"), Puppy("Bit")]
for a in animals {
println(a.introduce())
}Rex says woof Bit says yip
Only open methods can be overridden, and overriding always says override. An override fn is open itself.
#Super
super.method() calls the superclass's version of a method:
open class Greeter {
open fn greet(name: String): String = "Hello, {name}"
}
class LoudGreeter : Greeter() {
override fn greet(name: String): String = super.greet(name).uppercase() + "!"
}
println(LoudGreeter().greet("Ada"))HELLO, ADA!
#Interfaces
An interface lists methods a class promises to have. Methods can have a default body:
interface Shape {
fn area(): Float
fn describe(): String = "a shape with area {area()}"
}
class Square(let side: Float) : Shape {
override fn area(): Float = side * side
}
class Circle(let radius: Float) : Shape {
override fn area(): Float = PI * radius * radius
override fn describe(): String = "a circle"
}
let shapes: List<Shape> = [Square(2.0), Circle(1.0)]
for s in shapes {
println(s.describe())
}a shape with area 4.0 a circle
A class can implement any number of interfaces, after its superclass: class Dog(name: String) : Animal(name), Pet, Comparable. A class must implement every method that has no default body:
interface Speaker {
fn speak(): String
}
class Mute : Speaker {
}Type error: Mute must implement 'speak' from Speaker --> main.zyn:5:1 | 5 | class Mute : Speaker { | ^
#Generic classes
class Box<T>(let value: T) {
fn map<R>(f: (T) -> R): Box<R> = Box(f(value))
}
class Stack<T> {
let items = mutableListOf<T>()
fn push(item: T) { items.add(item) }
fn pop(): T? = if items.isEmpty() { null } else { items.removeAt(items.size - 1) }
}
println(Box(21).map { it * 2 }.value)
let stack = Stack<String>()
stack.push("a")
stack.push("b")
println(stack.pop())
println(stack.pop())
println(stack.pop())42 b a null
#Type checks
is checks whether an object is of a class, and smart-casts it:
open class Vehicle
class Bike : Vehicle() {
fn ring(): String = "ring ring"
}
let v: Vehicle = Bike()
if v is Bike {
println(v.ring())
}
println(v is Vehicle)ring ring true
#Classes or data types?
data | class | |
|---|---|---|
| Can change | No (use copy) | Yes, with var properties |
== compares | The values | Identity (the same object) |
| Methods | Extension functions | In the body |
| Inheritance | No | open classes and interfaces |
In match patterns | Yes | No (use is) |