Câu hỏi phỏng vấn Kotlin
Câu hỏi

Provide a real use case when ...

Câu trả lời

Here is a real use case where inline classes can be useful in Kotlin:

Representing Primitive Types with Semantic Meaning

Imagine you have a function that calculates the area of a rectangle. The function takes the length and width as parameters:

kotlin Copy
fun calculateRectangleArea(length: Double, width: Double): Double {
    return length * width
}

However, this function doesn't provide any semantic meaning for the parameters. It's not clear if length represents the length of the rectangle or the width. To add more meaning, you can create inline classes to represent the length and width:

kotlin Copy
inline class Length(val value: Double)
inline class Width(val value: Double)

fun calculateRectangleArea(length: Length, width: Width): Double {
    return length.value * width.value
}

Now, when calling the function, it's clear which parameter represents the length and which represents the width:

kotlin Copy
val area = calculateRe...
senior

senior

Gợi ý câu hỏi phỏng vấn

junior

What is a primary constructor in Kotlin?

middle

What is a purpose of Companion Objects in Kotlin?

expert

What is the difference between * and Any in Kotlin generics?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào