gpt4 book ai didi

Kotlin 将字符串自动转换为 Enum

转载 作者:行者123 更新时间:2023-12-04 13:07:57 29 4
gpt4 key购买 nike

有没有办法将字符串自动转换或自动转换为枚举?
playground

enum class Direction {
north, south, west, east
}

fun main() {
val d: Direction = "north" // <== Fails here
}
附言
我要找 使用枚举的简洁方法 ,就像 TypeScript 中的文字(代数)字符串类型一样。
或者,或者,使以下代码工作,请不要那样 north 不合格且冲突 .
enum class Direction {
north, south, west, east
}

enum class Compass {
north, south, west, east
}

fun main() {
val d: Direction = north // <== Fails here
val c: Compass = north // <== Fails here
}
更新:
目前不可能,有 KT-16768问题,如果您想拥有此功能,请投票。

最佳答案

你想要的方式是不可能的。唯一接近的是静态方法 valueOf :

enum class Direction {
north, south, west, east
}

fun main() {
val d: Direction = Direction.valueOf("north")
println(d)
// Prints north
}

关于Kotlin 将字符串自动转换为 Enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68535683/

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