gpt4 book ai didi

Kotlin 枚举就像在 swift 中一样

转载 作者:行者123 更新时间:2023-12-05 01:04:51 25 4
gpt4 key购买 nike

我在swift中有枚举

enum Type {
case bool(Bool)
case int(Int)
case array([String])
}

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

enum class AnswerSheetType {
BOOL,
INT,
ARRAY
}

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

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)
}
}

最佳答案

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

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

}

用法:

// 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}")
}

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

关于Kotlin 枚举就像在 swift 中一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71321484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com