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

Where should I use var and where val ?

expert

Why do we use companion object as a kind of replacement for Java static fields 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