Provide a real use case when ...
Provide a real use case when ...
Here is a real use case where inline classes can be useful in Kotlin:
Imagine you have a function that calculates the area of a rectangle. The function takes the length and width as parameters:
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:
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:
val area = calculateRe...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào