Polymorphism
suggest changePolymorphism means that one piece of code can work with values of many different types. You write shape.area() once, and the right implementation runs for a circle, a rectangle or a triangle.
Kotlin supports several kinds of polymorphism:
- subtype polymorphism: a variable of type
Shapeholds aCircle, and calls are dispatched toCircle's overrides at runtime - closed polymorphism with
sealedclasses and exhaustivewhen - ad-hoc polymorphism: function overloading, resolved at compile time
- parametric polymorphism: generic functions and classes that work for any type
T - functional polymorphism: passing behavior as lambdas or
fun interfaceinstances
This article shows each of them and the places where Kotlin's rules differ from what you might expect (extension functions, overloads, constructors).
Subtype polymorphism with open classes
Classes and members in Kotlin are final by default. To allow overriding, mark the class and the member open (see Basics: the open keyword). Subclasses must use the override modifier:
open class Animal(val name: String) {
open fun sound(): String = "..."
fun introduce() = println("$name says ${sound()}")
}
class Dog(name: String) : Animal(name) {
override fun sound() = "Woof"
}
class Cat(name: String) : Animal(name) {
override fun sound() = "Meow"
}
class Fish(name: String) : Animal(name)
fun main() {
val animals: List<Animal> = listOf(Dog("Rex"), Cat("Tom"), Fish("Nemo"))
for (a in animals) {
a.introduce()
}
}
Output:
Rex says Woof
Tom says Meow
Nemo says ...
introduce() is defined once in Animal and is not overridden, but the call to sound() inside it is dynamically dispatched: the JVM looks at the actual runtime class of the object, not the declared type Animal. Fish doesn't override sound(), so it inherits the base implementation.
Abstract classes
When there is no sensible default implementation, make the member abstract. An abstract class can't be instantiated, and every concrete subclass must implement the abstract members. Abstract members are implicitly open:
import kotlin.math.PI
abstract class Shape(val name: String) {
abstract fun area(): Double
// template method: common logic that calls the polymorphic part
fun describe() = "%s with area %.2f".format(name, area())
}
class Circle(val radius: Double) : Shape("Circle") {
override fun area() = PI * radius * radius
}
class Rectangle(val width: Double, val height: Double) : Shape("Rectangle") {
override fun area() = width * height
}
fun main() {
val shapes = listOf(Circle(1.0), Rectangle(2.0, 3.0), Circle(2.5))
shapes.forEach { println(it.describe()) }
val total = shapes.sumOf { it.area() }
println("Total area: %.2f".format(total))
}
Output:
Circle with area 3.14
Rectangle with area 6.00
Circle with area 19.63
Total area: 28.78
describe() is a template method: the base class fixes the overall algorithm and subclasses fill in the varying step.
Interfaces
A class can extend only one class but implement any number of interfaces. Interface members are abstract unless they have a body, and they are always open (see Interface with default implementations):
interface Drawable {
fun draw(): String
}
interface Clickable {
fun click(): String
fun showOff() = "I'm clickable!"
}
class Button(val label: String) : Drawable, Clickable {
override fun draw() = "[ $label ]"
override fun click() = "$label was clicked"
}
class Image(val file: String) : Drawable {
override fun draw() = "<img $file>"
}
fun render(items: List<Drawable>) {
items.forEach { println(it.draw()) }
}
fun main() {
val ok = Button("OK")
render(listOf(ok, Image("logo.png")))
val clickable: Clickable = ok
println(clickable.click())
println(clickable.showOff())
}
Output:
[ OK ]
<img logo.png>
OK was clicked
I'm clickable!
The same Button object is used polymorphically through two different interface types. If two interfaces provide default implementations of the same member, the class must override it and choose explicitly with super<Name>.member(); see Conflicts when Implementing Multiple Interfaces with Default Implementations.
Calling the base implementation with super
An override can extend the inherited behavior instead of replacing it:
open class Notifier {
open fun send(message: String) {
println("log: $message")
}
}
class EmailNotifier(val to: String) : Notifier() {
override fun send(message: String) {
super.send(message)
println("email to $to: $message")
}
}
fun main() {
val n: Notifier = EmailNotifier("ann@example.com")
n.send("Build passed")
}
Output:
log: Build passed
email to ann@example.com: Build passed
Overriding properties
Properties are polymorphic too. A property can be abstract or open and overridden with a value, a custom getter or a constructor parameter. A val can be overridden by a var (adding a setter), but not the other way around:
abstract class Vehicle {
abstract val wheels: Int
open val description: String
get() = "${this::class.simpleName} with $wheels wheels"
}
class Bike : Vehicle() {
override val wheels = 2
}
class Truck(override val wheels: Int) : Vehicle() {
override val description: String
get() = "Heavy truck, $wheels wheels"
}
class Car : Vehicle() {
override var wheels: Int = 4
}
fun main() {
val vehicles = listOf(Bike(), Truck(18), Car())
vehicles.forEach { println(it.description) }
}
Output:
Bike with 2 wheels
Heavy truck, 18 wheels
Car with 4 wheels
More examples are in Overriding properties and methods.
Covariant return types
An override may return a more specific type than the member it overrides. Callers that know the concrete type get the precise type without a cast:
open class Document {
open fun copy(): Document = Document()
}
class Invoice(val number: Int) : Document() {
override fun copy(): Invoice = Invoice(number)
}
fun main() {
val original = Invoice(42)
val clone: Invoice = original.copy() // no cast needed
println(clone.number)
}
Output:
42
Stopping further overriding with final override
A member marked override is itself open. To prevent subclasses from overriding it again, use final override:
open class Base {
open fun id() = "base"
}
open class Middle : Base() {
final override fun id() = "middle"
}
class Leaf : Middle() {
// override fun id() = "leaf"
// error: 'id' in 'Middle' is final and cannot be overridden
}
fun main() {
println(Leaf().id())
}
Output:
middle
Closed polymorphism with sealed classes
With open classes anyone can add a new subtype. Sometimes you want the opposite: a fixed set of cases that the compiler knows about. A sealed class or interface can only be subclassed in the same package and module, so when over it can be checked for exhaustiveness:
import kotlin.math.PI
sealed interface Shape
data class Circle(val radius: Double) : Shape
data class Rectangle(val width: Double, val height: Double) : Shape
data class Triangle(val base: Double, val height: Double) : Shape
fun area(shape: Shape): Double = when (shape) {
is Circle -> PI * shape.radius * shape.radius
is Rectangle -> shape.width * shape.height
is Triangle -> shape.base * shape.height / 2
// no else branch needed: the compiler knows all subtypes
}
fun main() {
val shapes = listOf(Circle(1.0), Rectangle(2.0, 3.0), Triangle(4.0, 5.0))
for (s in shapes) {
println("$s -> %.2f".format(area(s)))
}
}
Output:
Circle(radius=1.0) -> 3.14
Rectangle(width=2.0, height=3.0) -> 6.00
Triangle(base=4.0, height=5.0) -> 10.00
Inside each branch, shape is smart cast to the matched subtype, so shape.radius compiles without an explicit cast. If you add a Square subtype later, every when that doesn't handle it becomes a compile error, which is exactly what you want.
The two styles make opposite trade-offs:
Virtual methods (open/abstract) |
Sealed + when |
|
|---|---|---|
| Add a new type | easy: one new class | must update every when |
| Add a new operation | must update every class | easy: one new function |
| Who can add types | anyone (if open) | only the defining module |
Sealed hierarchies are a good fit for results, events, UI states and AST nodes. Virtual methods are a better fit for plugin-style extension points.
Prefer polymorphism over type checks
A chain of is checks over an open hierarchy is usually a sign that the behavior belongs in the classes:
// fragile: every new Animal subclass needs a new branch here
fun soundOf(a: Animal): String = when (a) {
is Dog -> "Woof"
is Cat -> "Meow"
else -> "..."
}
With sound() as an open member, the when disappears and new subclasses work automatically. Type checks are fine for sealed hierarchies, where the compiler guarantees all cases are covered.
Extension functions are not polymorphic
Extension functions look like members but are resolved statically, using the declared type of the expression, not the runtime type:
open class Shape
class Circle : Shape()
fun Shape.name() = "Shape"
fun Circle.name() = "Circle"
fun printName(s: Shape) {
println(s.name())
}
fun main() {
val c = Circle()
println(c.name()) // static type is Circle
printName(c) // static type is Shape
}
Output:
Circle
Shape
Inside printName the parameter's type is Shape, so Shape.name() is chosen at compile time even though the object is a Circle. If you need runtime dispatch, make the function an open member.
Also, when a class has a member and an extension with the same signature, the member always wins.
Overloading: compile-time polymorphism
Overloading means several functions with the same name and different parameter types. Like extensions, the choice is made at compile time from the static types of the arguments:
fun describe(x: Int) = "Int: $x"
fun describe(x: String) = "String: \"$x\""
fun describe(x: Any) = "Any: $x"
fun main() {
println(describe(42))
println(describe("hello"))
println(describe(3.5))
val hidden: Any = "hello"
println(describe(hidden))
}
Output:
Int: 42
String: "hello"
Any: 3.5
Any: hello
The last call passes a String at runtime, but the variable is declared as Any, so describe(Any) is picked. Overriding is dispatched on the runtime type of the receiver; overloading is resolved on the static types of the arguments.
Default arguments often replace a family of overloads in Kotlin:
fun greet(name: String, greeting: String = "Hello", punctuation: String = "!") =
"$greeting, $name$punctuation"
fun main() {
println(greet("Ann"))
println(greet("Bob", "Hi"))
println(greet("Cid", punctuation = "?"))
}
Output:
Hello, Ann!
Hi, Bob!
Hello, Cid?
Parametric polymorphism with generics
Generic code works uniformly for any type argument. An upper bound restricts T to types that support the operations you need (see Generics):
fun <T : Comparable<T>> largest(items: List<T>): T {
require(items.isNotEmpty()) { "empty list" }
var max = items[0]
for (item in items) {
if (item > max) max = item
}
return max
}
class Box<T>(val value: T) {
fun <R> map(transform: (T) -> R): Box<R> = Box(transform(value))
override fun toString() = "Box($value)"
}
fun main() {
println(largest(listOf(3, 9, 2)))
println(largest(listOf("pear", "apple", "zucchini")))
val b = Box(21).map { it * 2 }.map { "answer=$it" }
println(b)
}
Output:
9
zucchini
Box(answer=42)
Variance: subtyping of generic types
Is a List<Dog> a List<Animal>? In Kotlin, yes, because the read-only List<out E> is declared covariant. A MutableList<Dog> is not a MutableList<Animal>, because otherwise you could add a Cat to a list of dogs:
open class Animal(val name: String)
class Dog(name: String) : Animal(name)
fun names(animals: List<Animal>) = animals.joinToString { it.name }
fun main() {
val dogs: List<Dog> = listOf(Dog("Rex"), Dog("Fido"))
println(names(dogs)) // OK: List is covariant
val mutableDogs: MutableList<Dog> = mutableListOf(Dog("Rex"))
println(names(mutableDogs)) // OK: MutableList<Dog> is a List<Animal>
// val animals: MutableList<Animal> = mutableDogs
// error: initializer type mismatch: expected 'MutableList<Animal>', actual 'MutableList<Dog>'
// (MutableList is invariant)
}
Output:
Rex, Fido
Rex
Use out T on your own types when they only produce T, and in T when they only consume it.
Functional polymorphism: lambdas and fun interfaces
You don't always need a class hierarchy. If the varying behavior is a single function, pass a function:
fun interface Discount {
fun apply(price: Double): Double
}
val noDiscount = Discount { it }
val tenPercent = Discount { it * 0.9 }
fun fixed(amount: Double) = Discount { maxOf(0.0, it - amount) }
fun checkout(prices: List<Double>, discount: Discount): Double =
prices.sumOf { discount.apply(it) }
fun main() {
val cart = listOf(20.0, 35.5, 4.5)
println("%.2f".format(checkout(cart, noDiscount)))
println("%.2f".format(checkout(cart, tenPercent)))
println("%.2f".format(checkout(cart, fixed(5.0))))
}
Output:
60.00
54.00
45.50
A fun interface (single abstract method interface) can be implemented with a lambda, and still has a proper name, so it reads better in signatures than (Double) -> Double. A class can also implement it the normal way when the behavior needs state.
Composition with delegation
Inheritance is not the only way to reuse behavior polymorphically. With by, a class implements an interface by forwarding to another object and overrides only what it needs (see Class Delegation):
interface Logger {
fun info(msg: String)
fun error(msg: String)
}
class ConsoleLogger : Logger {
override fun info(msg: String) = println("INFO $msg")
override fun error(msg: String) = println("ERROR $msg")
}
class CountingLogger(private val inner: Logger) : Logger by inner {
var errors = 0
private set
override fun error(msg: String) {
errors++
inner.error(msg)
}
}
fun process(log: Logger) {
log.info("starting")
log.error("disk full")
log.error("retry failed")
}
fun main() {
val logger = CountingLogger(ConsoleLogger())
process(logger)
println("errors: ${logger.errors}")
}
Output:
INFO starting
ERROR disk full
ERROR retry failed
errors: 2
process only knows about Logger. CountingLogger is a decorator: it wraps any Logger without having to subclass a concrete class.
Pitfall: calling open members from a constructor
The base class constructor runs before the subclass's properties are initialized. If it calls an open member, the override runs on a half-built object:
open class Base {
init {
println("Base init: ${describe()}")
}
open fun describe() = "base"
}
class Derived(val name: String) : Base() {
override fun describe() = "derived, name=$name"
}
fun main() {
val d = Derived("widget")
println("After construction: ${d.describe()}")
}
Output:
Base init: derived, name=null
After construction: derived, name=widget
name is declared as non-null String, yet it is null while Base's initializer runs. Calling a method on it there would throw NullPointerException. IntelliJ IDEA flags this with a "Calling non-final function in constructor" inspection. Avoid calling open members from constructors and init blocks; see Constructors and init blocks for the initialization order.
Polymorphism through Any
Every Kotlin class inherits from Any, which declares open toString(), equals() and hashCode(). Library code like println, string templates, Set and Map calls them polymorphically:
class Point(val x: Int, val y: Int) {
override fun toString() = "($x, $y)"
override fun equals(other: Any?) = other is Point && x == other.x && y == other.y
override fun hashCode() = 31 * x + y
}
fun main() {
val items: List<Any> = listOf(1, "two", Point(3, 4), mutableListOf(5))
items.forEach { println("${it::class.simpleName}: $it") }
val set = setOf(Point(1, 2), Point(1, 2))
println(set.size)
}
Output:
Int: 1
String: two
Point: (3, 4)
ArrayList: [5]
1
The ArrayList line shows that it::class reports the runtime class, not the declared type. data class generates these three overrides for you.
Choosing an approach
- Use an interface to define a capability that unrelated classes can share.
- Use an abstract class when subclasses share state or a template algorithm.
- Use a sealed hierarchy when the set of cases is fixed and you want exhaustive
when. - Use a lambda or
fun interfacewhen the varying behavior is a single function. - Use delegation to add behavior around an existing implementation instead of subclassing it.
- Remember that extension functions and overloads are resolved at compile time; only member overrides dispatch on the runtime type.