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

senior

What is Kotlin backing field is used for?

middle

What are scope functions in Kotlin?

junior

What is a data class in Kotlin?

Bình luận

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

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