Type aliases
Type aliases provide alternative names for existing types. They can make long or frequently used type expressions shorter and easier to understand.
For example, you can create aliases for generic types, function types, and nested or inner classes:
A type alias doesn't create a new type. It introduces an alternative name for an existing type. The alias and its underlying type are interchangeable. For example, when you add typealias Predicate<T> and use Predicate<Int>, the compiler expands it to (Int) -> Boolean. You can use a value declared with the alias wherever the underlying type is expected, and the other way around:
Declare type aliases
You can declare a type alias:
At the top level of a Kotlin file, as a top-level type alias.
Inside a class, interface, or object, as a nested type alias.
You can't declare a type alias in a local scope, such as inside a function or lambda expression.
The declaration location determines the scope of a type alias, while its visibility determines which code can access it. By default, a type alias is public. A nested type alias is accessible only where its containing class, interface, or object is accessible. For example, a public alias inside an internal class isn't accessible from outside the module.
A type alias can't expose an underlying type with more restrictive visibility than its own. For example, a public type alias can't refer to a private class.
Top-level type aliases
A top-level type alias is a package-level declaration. Within the same package, you can refer to an alias by its unqualified name. To use the alias from another package, import the alias or refer to it by its qualified name:
Nested type aliases
Nested type aliases allow for cleaner, more maintainable code by improving encapsulation, reducing package-level clutter, and simplifying internal implementations. Nested type aliases follow the same scope and name-resolution rules as nested classes.
Declare a type alias inside a class, interface, or object when the alternative name is relevant only in the context of that declaration. This keeps the alias close to the code that uses it and avoids adding another name to the package scope.
Within the containing declaration, you can refer to the alias by its unqualified name. Outside the declaration, qualify the alias with the name of its containing declaration:
Type parameters
To use type parameters in a nested type alias, add them to the alias declaration:
In this example, Path declares its type parameter T. In Graph.Path<String>, String is the type argument for T and is independent of the Node type parameter declared by Graph.
If you refer to a type parameter declared by its containing class or interface, the compiler reports an error:
Here, Path refers to Node from Graph instead of declaring its own type parameter.