Type aliases
Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead.
It's useful to shorten long generic types. For instance, it's often tempting to shrink collection types:
You can provide different aliases for function types:
You can have new names for inner and nested classes:
Type aliases do not introduce new types. They are equivalent to the corresponding underlying types. When you add typealias Predicate<T>
and use Predicate<Int>
in your code, the Kotlin compiler always expands it to (Int) -> Boolean
. Thus you can pass a variable of your type whenever a general function type is required and vice versa:
Nested type aliases
In Kotlin, you can define type aliases inside other declarations, as long as they don't capture type parameters from their outer class:
Capturing means that the type alias refers to a type parameter defined in the outer class:
To fix this issue, declare the type parameter directly in the type alias:
Nested type aliases allow for cleaner, more maintainable code by improving encapsulation, reducing package-level clutter, and simplifying internal implementations.
Rules for nested type aliases
Nested type aliases follow specific rules to ensure clear and consistent behavior:
Nested type aliases must follow all existing type alias rules.
In terms of visibility, the alias can't expose more than its referenced types allow.
Their scope is the same as nested classes. You can define them inside classes, and they hide any parent type aliases with the same name as they don't override.
Nested type aliases can be marked as
internal
orprivate
to limit their visibility.Nested type aliases are not supported in Kotlin Multiplatform's
expect/actual
declarations.
How to enable nested type aliases
To enable nested type aliases in your project, use the following compiler option in the command line:
Or add it to the compilerOptions {}
block of your Gradle build file: