Kotlin Class: Inline class email for type-safe email address representation
Write a Kotlin program that creates an inline class 'Email' that represents an email address. Use the inline class to enforce type safety.
Pre-Knowledge (Before You Start!)
Before attempting this exercise, you should be familiar with the following concepts:
- Inline Classes: A feature in Kotlin that allows wrapping a single value in a class while improving performance by avoiding object overhead.
- Type Safety: Ensuring that values are used correctly by restricting them to specific types.
- Functions in Kotlin: Understanding how to define and call functions with parameters.
- Printing to Console: Using println() to display messages.
Hints (Try Before Looking at the Solution!)
Try to solve the problem using these hints:
- Hint 1: Define an inline class named Email that takes a single string parameter.
- Hint 2: Create a function named sendEmail() that accepts an Email type parameter.
- Hint 3: In the main() function, create an instance of the Email class with an email address.
- Hint 4: Pass the email instance to the sendEmail() function and print the email being sent.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics