Nested type aliases
suggest changeA type alias gives a new name to an existing type. For a long time Kotlin only allowed them at the top level of a file. That is a problem for short, common names like Callback, Listener or Handler: a top-level typealias Callback is visible in the whole package, so two classes can't each have their own Callback.
Since Kotlin 2.3 you can declare a typealias inside a class, interface or object. The alias then belongs to that type and you refer to it as UserRepository.Callback, the same way you refer to a nested class.
Versions:
- Kotlin 1.1: top-level type aliases.
- Kotlin 2.2: nested type aliases in Beta, enabled with the
-Xnested-type-aliasescompiler flag. - Kotlin 2.3: nested type aliases are stable. No flag is needed.
- Kotlin 2.4: still stable. Passing
-Xnested-type-aliasesonly produces a "redundant" warning. Local type aliases (inside a function body) are still experimental.
All examples were compiled and run with Kotlin 2.4.21 on JDK 25.
Declaring a nested type alias
Put the typealias in the class body. Inside the class, use the short name. Outside, qualify it with the class name:
data class User(val id: Int, val name: String)
class UserRepository {
typealias Callback = (Result<User>) -> Unit
typealias Listener = (event: String, user: User) -> Unit
private val users = mutableMapOf(1 to User(1, "Ann"))
private val listeners = mutableListOf<Listener>()
fun addListener(listener: Listener) {
listeners += listener
}
fun load(id: Int, callback: Callback) {
val user = users[id]
if (user == null) {
callback(Result.failure(NoSuchElementException("no user $id")))
} else {
listeners.forEach { it("loaded", user) }
callback(Result.success(user))
}
}
}
class ImageCache {
// the same short name, no clash
typealias Callback = (ByteArray?) -> Unit
fun get(url: String, callback: Callback) = callback(null)
}
fun main() {
val repo = UserRepository()
repo.addListener { event, user -> println("$event ${user.name}") }
val printUser: UserRepository.Callback = { result ->
result
.onSuccess { println("got $it") }
.onFailure { println("error: ${it.message}") }
}
repo.load(1, printUser)
repo.load(2, printUser)
val onImage: ImageCache.Callback = { bytes -> println("image: ${bytes?.size}") }
ImageCache().get("https://example.com/a.png", onImage)
}
loaded Ann
got User(id=1, name=Ann)
error: no user 2
image: null
UserRepository.Callback and ImageCache.Callback are two unrelated aliases. Each stays next to the API that uses it.
Naming function types is the most common use, but the right-hand side can be any type, including generic types:
class Graph {
typealias Edge = Pair<String, String>
typealias Adjacency = MutableMap<String, MutableSet<String>>
private val adjacency: Adjacency = mutableMapOf()
fun add(edge: Edge) {
adjacency.getOrPut(edge.first) { mutableSetOf() } += edge.second
}
fun neighbors(node: String): Set<String> = adjacency[node].orEmpty()
}
fun main() {
val g = Graph()
// an alias to a class can be used to call its constructor
g.add(Graph.Edge("a", "b"))
g.add(Graph.Edge("a", "c"))
g.add("b" to "c")
println(g.neighbors("a"))
println(g.neighbors("b"))
}
[b, c]
[c]
Graph.Edge("a", "b") calls the Pair constructor. "b" to "c" creates a plain Pair<String, String>, and add() accepts it because Edge is that type.
Where you can declare them
Nested type aliases are allowed in classes, interfaces, objects, companion objects and inner classes:
interface Shape {
typealias Point = Pair<Double, Double>
val center: Point
}
object Config {
typealias Settings = Map<String, String>
val defaults: Settings = mapOf("theme" to "dark")
}
class Matrix(val rows: Int, val cols: Int) {
companion object {
typealias Cells = Array<DoubleArray>
fun zeros(rows: Int, cols: Int): Cells = Array(rows) { DoubleArray(cols) }
}
// inside the class the companion's alias is visible unqualified
val cells: Cells = zeros(rows, cols)
inner class Row(val index: Int) {
typealias Values = List<Double>
fun values(): Values = cells[index].toList()
}
}
class Circle(override val center: Shape.Point, val r: Double) : Shape
fun main() {
val c = Circle(1.0 to 2.0, 3.0)
val p: Shape.Point = c.center
println(p)
val s: Config.Settings = Config.defaults
println(s)
val m = Matrix(2, 3)
val cells: Matrix.Companion.Cells = m.cells
println(cells.size)
val v: Matrix.Row.Values = m.Row(0).values()
println(v)
}
(1.0, 2.0)
{theme=dark}
2
[0.0, 0.0, 0.0]
An alias in a companion object is a member of the companion, not of the class. From outside you must write Matrix.Companion.Cells. Matrix.Cells doesn't resolve:
fun main() {
val x: Matrix.Cells = Matrix.zeros(1, 1)
}
a3.kt:2:19: error: unresolved reference 'Cells'.
val x: Matrix.Cells = Matrix.zeros(1, 1)
^^^^^
So prefer putting aliases directly in the class body. A companion is only worth it if you also want the alias next to factory functions.
Inside a function body (a local alias, or an alias in a local class) it's still an error in Kotlin 2.4 unless you opt into an experimental feature:
error: the feature "local type aliases" is experimental and should be enabled explicitly. This can be done by supplying the compiler argument '-Xlocal-type-aliases', but note that no stability guarantees are provided.
Importing a nested alias
A nested alias can be imported like a nested class, optionally renamed with as:
// file http.kt
package net.http
class HttpClient {
typealias Headers = Map<String, List<String>>
typealias Handler = (status: Int, headers: Headers, body: String) -> Unit
fun get(url: String, handler: Handler) {
handler(200, mapOf("Content-Type" to listOf("text/plain")), "hello from $url")
}
}
// file main.kt
import net.http.HttpClient
import net.http.HttpClient.Handler
import net.http.HttpClient.Headers as HttpHeaders
fun contentType(headers: HttpHeaders): String? = headers["Content-Type"]?.firstOrNull()
val logResponse: Handler = { status, headers, body ->
println("$status ${contentType(headers)}: $body")
}
fun main() {
HttpClient().get("example.com", logResponse)
}
200 text/plain: hello from example.com
Code that uses the alias a lot can import it. Everyone else sees the qualified HttpClient.Headers, which says where the name comes from.
Visibility
Nested aliases accept the same visibility modifiers as other members: public (the default), internal, protected and private.
open class Cache {
private typealias Entries = MutableMap<String, Pair<Long, String>>
protected typealias Clock = () -> Long
internal typealias Stats = Pair<Int, Int>
private val entries: Entries = mutableMapOf()
protected open val clock: Clock = System::currentTimeMillis
private var hits = 0
private var misses = 0
fun put(key: String, value: String) {
entries[key] = clock() to value
}
fun get(key: String): String? {
val e = entries[key]
if (e == null) misses++ else hits++
return e?.second
}
internal fun stats(): Stats = hits to misses
}
class TestCache : Cache() {
// a subclass can use the protected alias
override val clock: Clock = { 42L }
}
fun main() {
val cache = TestCache()
cache.put("a", "apple")
println(cache.get("a"))
println(cache.get("b"))
val stats: Cache.Stats = cache.stats()
println(stats)
}
apple
null
(1, 1)
Outside the class, the private and protected aliases can't be named:
fun main() {
val e: Cache.Entries = mutableMapOf()
val c: Cache.Clock = { 0L }
}
v2.kt:2:18: error: cannot access 'typealias Entries = MutableMap<String, Pair<Long, String>>': it is private in 'Cache'.
val e: Cache.Entries = mutableMapOf()
^^^^^^^
v2.kt:3:18: error: cannot access 'typealias Clock = () -> Long': it is protected in 'Cache'.
val c: Cache.Clock = { 0L }
^^^^^
The visibility applies to the name, not to the type behind it. A public function may use a private alias in its signature. Callers just see the expanded type:
class Db {
private typealias Row = Map<String, Any?>
// a public function may use a private alias: callers see the expanded type
fun firstRow(): Row = mapOf("id" to 1, "name" to "Ann")
}
fun main() {
val row: Map<String, Any?> = Db().firstRow()
println(row["name"])
}
Ann
The reverse is not allowed. A public alias can't make a private type public:
class Parser {
private class Token(val text: String)
typealias PublicToken = Token
}
v4.kt:3:15: error: 'public' typealias exposes 'private-in-class' in expanded type 'Token'.
typealias PublicToken = Token
^^^^^^^^^^^
Aliases in subclasses
Nested aliases follow the same lookup rules as nested classes. In a subclass, aliases declared in a superclass are visible without qualification. Aliases declared in an interface are not: implementing classes must still write Interface.Alias.
interface EventSource {
typealias Handler = (name: String, payload: Any?) -> Unit
fun subscribe(handler: EventSource.Handler)
}
abstract class Widget : EventSource {
typealias Style = Map<String, String>
// an interface's aliases need qualification, like its nested classes
private val handlers = mutableListOf<EventSource.Handler>()
override fun subscribe(handler: EventSource.Handler) { handlers += handler }
protected fun fire(name: String, payload: Any?) = handlers.forEach { it(name, payload) }
abstract val style: Style
}
class Button(val label: String) : Widget() {
// a superclass's aliases are visible without qualification
override val style: Style = mapOf("color" to "blue")
fun click() = fire("click", label)
}
fun main() {
val b = Button("Save")
b.subscribe { name, payload -> println("event $name, payload $payload") }
println(b.style)
b.click()
}
{color=blue}
event click, payload Save
If Widget used a bare Handler, compilation would fail with unresolved reference 'Handler'.
Nested aliases can't capture type parameters
A nested type alias works like a nested (static) class, not an inner class. It has no access to the type parameters of the class it's declared in. This doesn't compile:
class Repository<T> {
typealias Callback = (List<T>) -> Unit
}
g1.kt:2:32: error: unresolved reference 'T'.
typealias Callback = (List<T>) -> Unit
^
That makes sense: you refer to the alias as Repository.Callback, with no type argument for Repository, so T would have no value. The fix is to give the alias its own type parameter and pass T where you use it:
class Repository<T>(private val items: List<T>) {
// the alias declares its own type parameter
typealias Callback<E> = (List<E>) -> Unit
typealias Predicate<E> = (E) -> Boolean
fun findAll(filter: Predicate<T>, callback: Callback<T>) {
callback(items.filter(filter))
}
}
fun main() {
val repo = Repository(listOf("apple", "banana", "cherry"))
val printAll: Repository.Callback<String> = { println(it) }
repo.findAll({ 'a' in it }, printAll)
val isLong: Repository.Predicate<String> = { it.length > 5 }
repo.findAll(isLong, printAll)
}
[apple, banana]
[banana, cherry]
The type argument goes on the alias (Repository.Callback<String>), not on the class.
The same rule catches a less obvious case. An inner class of a generic class implicitly depends on the outer type parameter: Node inside Tree<T> is really Tree<T>.Node. So an alias for it captures T even though T isn't written:
class Tree<T> {
inner class Node(val value: T)
typealias N = Node
}
t5.kt:3:19: error: type alias expansion captures outer type parameters: 'T' defined in 'Tree'.
typealias N = Node
^^^^
Spell out the outer type explicitly with its own parameter:
class Tree<T>(rootValue: T) {
inner class Node(val value: T) {
val children = mutableListOf<Node>()
fun add(value: T): Node = Node(value).also { children += it }
}
// Node is really Tree<T>.Node, so the outer T has to be passed in
typealias NodeOf<X> = Tree<X>.Node
typealias Visitor<X> = (node: NodeOf<X>, depth: Int) -> Unit
val root = Node(rootValue)
fun walk(visit: Visitor<T>) {
fun go(n: Node, depth: Int) {
visit(n, depth)
n.children.forEach { go(it, depth + 1) }
}
go(root, 0)
}
}
fun main() {
val tree = Tree("src")
val main: Tree.NodeOf<String> = tree.root.add("main")
main.add("App.kt")
tree.root.add("test")
tree.walk { node, depth -> println(" ".repeat(depth) + node.value) }
}
src
main
App.kt
test
Aliases in a non-generic class, or aliases that only mention their own type parameters, never have this problem.
A type alias is not a new type
Nesting changes where the name lives, not what an alias is. The alias and the type it stands for are fully interchangeable. Two aliases for Long are both just Long:
class Orders {
typealias OrderId = Long
typealias CustomerId = Long
fun cancel(order: OrderId, by: CustomerId) = println("order $order cancelled by $by")
}
fun main() {
val order: Orders.OrderId = 1001
val customer: Orders.CustomerId = 7
val orders = Orders()
orders.cancel(order, customer)
orders.cancel(customer, order) // compiles: both are just Long
val sum: Long = order + customer
println(sum)
}
order 1001 cancelled by 7
order 7 cancelled by 1001
1008
The swapped arguments compile without a warning. If you want the compiler to stop that, you need a real type. A value class gives you one, usually with no runtime cost:
class Orders {
@JvmInline value class OrderId(val raw: Long)
@JvmInline value class CustomerId(val raw: Long)
fun cancel(order: OrderId, by: CustomerId) = println("order ${order.raw} cancelled by ${by.raw}")
}
fun main() {
val order = Orders.OrderId(1001)
val customer = Orders.CustomerId(7)
Orders().cancel(order, customer)
Orders().cancel(customer, order)
}
n2.kt:12:21: error: argument type mismatch: actual type is 'Orders.CustomerId', but 'Orders.OrderId' was expected.
Orders().cancel(customer, order)
^^^^^^^^
n2.kt:12:31: error: argument type mismatch: actual type is 'Orders.OrderId', but 'Orders.CustomerId' was expected.
Orders().cancel(customer, order)
^^^^^
Use an alias to make a long type readable. Use a value class when mixing up two values of the same underlying type would be a bug.
Aliases also leave nothing in the bytecode. Compiling the first example produces no class for UserRepository.Callback. javap shows the expanded function types, and that's also what Java callers see:
$ javap -cp out UserRepository
Compiled from "a1.kt"
public final class UserRepository {
public UserRepository();
public final void addListener(kotlin.jvm.functions.Function2<? super java.lang.String, ? super User, kotlin.Unit>);
public final void load(int, kotlin.jvm.functions.Function1<? super kotlin.Result<User>, kotlin.Unit>);
}
Older language versions
Nested aliases need language version 2.3 or later. If a project pins an older languageVersion, the compiler says so:
$ kotlinc -language-version 2.2 t1.kt
t1.kt:2:5: error: the feature "nested type aliases" is only available since language version 2.3
typealias Callback = (T) -> Unit
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
With language version 2.2 you can still enable the Beta version with -Xnested-type-aliases. In Gradle:
kotlin {
compilerOptions {
freeCompilerArgs.add("-Xnested-type-aliases")
}
}
On 2.3 and newer, remove the flag.
Summary
- Declare
typealiasinside a class, interface, object or companion object (Kotlin 2.3+). Refer to it asOuter.Alias, or import it. - Aliases in a companion object are reached through
Outer.Companion.Alias. - Visibility modifiers work as for other members. A public alias can't expose a private type, but a public function may use a private alias.
- Superclass aliases are visible unqualified in subclasses. Interface aliases are not.
- A nested alias can't use the outer class's type parameters. Give it its own (
typealias Callback<E> = (List<E>) -> Unit) and writeTree<X>.Nodefor inner classes. - An alias is only a name. Use a value class when you need a distinct type.