Kotlin 枚举就像在 swift 中一样

xkp*_*xzu 4 kotlin

我有快速枚举

enum Type {
    case bool(Bool)
    case int(Int)
    case array([String])
}
Run Code Online (Sandbox Code Playgroud)

不明白如何将其转换为 kotlin 代码,我确实是这样的:

enum class AnswerSheetType {
    BOOL,
    INT,
    ARRAY
}
Run Code Online (Sandbox Code Playgroud)

但是我如何将变量传递给枚举类型。例如,我想要创建方法,该方法将返回带变量的类型,如下所示(快速代码):

func marks(for id: String) -> Type {
    let answer = answers?[id]
    
    if let boolAnswer = answer as? Bool {
        return .bool(boolAnswer)
    }
    if let intAnswer = answer as? Int {
        return .int(intAnswer)
    }
    if let arrayAnswer = answer as? [String] {
        return .array(arrayAnswer)
    }
}
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 8

您可以使用密封接口/类来表示这一点。

sealed interface Type {

    data class BoolType(val value: Bool) : Type
    data class IntType(val value: Int) : Type
    data class ArrayType(val value: Array<String>) : Type

    // if you have a case that doesn't have any associated values, just use an object
    // object CaseWithoutAssociatedValues: Type

}
Run Code Online (Sandbox Code Playgroud)

用法:

// let someType: Type = .bool(true)
val someType: Type = Type.BoolType(true)

// just like how you can use a switch on a Swift enum, you can use a when like this too:
// This when is also exhaustive, if you specify all the implementers of Type
when (someType) {
    is Type.BoolType -> println("Bool value: ${someType.value}")
    is Type.IntType -> println("Int value: ${someType.value}")
    is Type.ArrayType -> println("Array value: ${someType.value}")
}
Run Code Online (Sandbox Code Playgroud)

someType.value请注意,由于智能转换,您可以在每个分支中访问。这与 Swift 不同,在 Swift 中,您需要进行模式匹配来获取关联的值。