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

senior

What is Coroutine Scope and how is that different from Coroutine Context?

expert

What is The Billion Dollar Mistake?

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