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

How can I create static m...

Câu trả lời

In Kotlin, you can create static methods for enums using companion objects. Here's how you can do it:

Creating Static Methods for Enums in Kotlin

  1. Define your enum class:
kotlin Copy
enum class Color {
    RED, GREEN, BLUE;

    companion object {
        fun getColorName(color: Color): String {
            return when (color) {
                RED -> "Red"
                GREEN -> "Green"
                BLUE -> "Blue"
            }
        }
    }
}
  1. In the enum class, define a companion object. This is where you can add your static methods.

  2. Inside the companion object, define your static method(s). In this example, we have a getColorName function that t...

senior

senior

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

junior

What is basic difference between fold and reduce in Kotlin? When to use which?

middle

Explain lazy initialization in Kotlin

middle

When would you use Elvis operator in Kotlin?

Bình luận

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

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