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

middle

Explain lazy initialization in Kotlin

middle

What are coroutines in Kotlin?

expert

Explain the difference between lateinit and lazy in details

Bình luận

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

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