Going through the Kotlin introductory course I reached typealias
and thought of something that I know from Swift:
typealias Person = (name: String, age: Int)
This looks from the usage site just like a minimalistic struct.
Simulating this does not seem to be possible in Kotlin: there are no parameter labels, and renaming properties is not a thing.
Why not? Syntax would have to be invented, but the semantics of this would be rather clear, I think:
typealias Person = Pair<String, Int>(name, age)
// or
typealias Person = Pair(name: String, age: Int)
Now, instead of first
and second
, Person
would have properties name
and age
. While this is not much shorter than creating a data class, it saves us (i.e. the compiler and runtime) having an extra class around.
I think this would work as long as the right-hand side of a typealias is a data class.
And if we want to add methods later, we can change the typealias into a data class without breaking usage sites:
data class Person(val name: String, val age: Int) {
fun isOld() = age >= 30
}
What do you think?