w3resource

Kotlin Class: Inline class email for type-safe email address representation

Kotlin Class: Exercise-19 with Solution

Write a Kotlin program that creates an inline class 'Email' that represents an email address. Use the inline class to enforce type safety.

Sample Solution:

Kotlin Code:

inline class Email(val value: String)

fun sendEmail(email: Email) {
    println("Sending email to ${email.value}")
}

fun main() {
    val email = Email("[email protected]")
    sendEmail(email)
}

Sample Output:

Sending email to [email protected]

Explanation:

In the above exercise -

  • We define an inline class "Email" with a single property value of type String. The Email class is marked as inline, which allows it to be used as a wrapper type with improved performance and type safety.
  • We also define a function "sendEmail(()" that takes an argument of type Email and prints the email address.
  • In the "main()" function, we create an instance of the "Email" class with the email address "[email protected]". We then pass this instance to the "sendEmail()" function.

Kotlin Editor:


Previous: Enum class Color for Object color representation.
Next: MathConstants object for Mathematical constants.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/kotlin-exercises/class/kotlin-class-exercise-19.php