• +91 9723535972
  • info@interviewmaterial.com

Kotlin Interview Questions and Answers

Question - Provide a real use case when inline classes may be useful

Answer -

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"))
}

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners