![]() This highlights another important feature of type aliases: the alias has identical semantics to the aliased type. the a to b infix operator for constructing Pairs, and the interaction between Pair and Map), this would sacrifice the clarity of having properties named “username” and “passwordHash” (rather than “first” and “second”) to little advantage. We could define Credentials like this: typealias Credentials = Pairīut unless we wanted to use the semantics of Pair when handling Credentials (i.e. ![]() However, tuples were deliberately removed from Kotlin, in favour of data classes which provide explicit property names (rather than relying on positional indexing for properties). If Kotlin supported a tuple construct, we might be able to write something like: typealias Credentials = (UserName, PasswordHash) Reading these type declarations, we know the fundamental types and type transformations that the part of the program that uses them is going to be about. Typealias HashFunction = (Password) -> PasswordHashĭata class Credentials(val username: UserName, val passwordHash: PasswordHash) In particular, they enable us to express the domain of some part of a program in a very concise way: typealias UserName = String ![]() However, they’re very convenient for the programmer. They’re invisible to the underlying type system, which sees things only in black-and-white, so they’re neither checked by the compiler nor visible at run-time using reflection. Type aliases at this level are like a sort of colour-coding on types. ![]() Val password1: PasswordHash = hash("p4ssw0rd") So we can assign freely, but also incorrectly: val userName1: UserName = "user1" However, we cannot use type aliases to constrain parameters: a function accepting a PasswordHash parameter will accept any String value for that parameter. This can save us having to create wrapper classes like: data class UserName(name: String) An immediately useful consequence of type aliases is that common types can be given aliases that more clearly communicate intent: typealias UserName = String
0 Comments
Leave a Reply. |