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 the idiomatic way to remove duplicate strings from array?

middle

How is it recommended to create constants in Kotlin?

middle

What is lateinit in Kotlin and when would you use it?

Bình luận

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

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