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. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |