Provide a real use case when inline classes may be useful

Technology CommunityCategory: KotlinProvide a real use case when inline classes may be useful
VietMX Staff asked 3 years ago

Imagine an authentication method in an API that looks as follows:

fun auth(userName: String, password: String) { println("authenticating $userName.") }

Since both parameters are of type String, you may mess up their order which gets even more likely with an increasing number of arguments.

Inline class wrappers around these types can help you mitigate that risk and give you simple, type-safe wrappers without introducing additional heap allocations:

inline class Password(val value: String)
inline class UserName(val value: String)

fun auth(userName: UserName, password: Password) { println("authenticating $userName.")}

fun main() {
    auth(UserName("user1"), Password("12345"))
    //does not compile due to type mismatch
    auth(Password("12345"), UserName("user1"))
}