Read on to find an introduction to type aliases, including generic variants, what they are and what they arenβt, and how a simple type alias can have a profound influence on how readable your code is.
Kotlin allows you to define type aliases, which are simply placeholders for other types.. These can be useful to shorten long verbose types into something more manageable, as well as giving meaning to nonspecific types.Β Pair<Long, Int>
Β could beΒ OnlineUserCountAtInstant
, for example.
//sampleStart import java.io.File typealias FileTable<K> = MutableMap<K, MutableList<File>> typealias MyHandler = (Int, String, Any) -> Unit typealias Predicate<T> = (T) -> Boolean //sampleEnd fun main() { val poem = """ When you're in the symphony of code's melody, Kotlin's syntax is the harmony so free. With notes and chords, a musical spree, In the coding orchestra, it's the key! """.trimIndent() println(poem) }
A proper choice of type alias can have a profound influence on how readable your code is.
For example:
//sampleStart interface Tree<T> sealed interface FilesystemObject interface File : FilesystemObject interface Directory : FilesystemObject typealias Filesystem = Tree<FilesystemObject> typealias Path = List<String> typealias Paths = Set<Path> typealias RegisteredBackupPaths = Map<Filesystem, Paths> // Compare this fun backupTypeAliased( what: RegisteredBackupPaths, where: Path ) {} // vs. this fun backupNotTypeAliased( what: Map<Tree<FilesystemObject>, Set<List<String>>>, where: List<String> ) {} //sampleEnd fun main() { val poem = """ Kotlin, the philosopher in code's discourse, With expressions and concepts, a powerful force. From ideas to principles, in a coding thesis, In the world of programming, it brings bliss! """.trimIndent() println(poem) }
However, it is extremely important to keep in mind thatΒ type aliases arenβt new types!Β The compiler always expands them to the type they represent, which can lead to mistakes if used improperly:
//sampleStart typealias FirstName = String typealias LastName = String fun printName(firstname: FirstName, lastname: LastName) = println(""" |First name: $firstname |Last name: $lastname """.trimMargin()) fun main() { val firstname: FirstName = "Peter" val lastname: LastName = "Quinn" // Compiles fine! printName(lastname, firstname) } //sampleEnd
Since both firstname
and lastname
are (type aliased) strings, thereβs nothing stopping you from accidentally flipping the two.
If you want to prevent errors like this, the next chapterβs got you covered.