你能帮我解释一下这个功能是如何工作的吗?它使用内联、具体化、valueOf() 和 enumValues

can you help me explaining how this function work? it uses Inline, reified, valueOf() and enumValues

我真的需要你的帮助来解释这个功能。 我有一个包含 2 个字符串值、国家名称和货币的国家/地区枚举。练习是使用 2 个字符串输入,检查枚举是否有国家,然后比较它们的货币,return true 或 false。我设法用 2 个 for 循环和 2 个 ifs 来做到这一点,但我知道这并不理想。 然后我尝试使用 contains()valueOf(input) 但是当输入不在枚举中时它会抛出 valueOf()

的非法参数异常
if (values().contains(valueOf(country1.toUpperCase())) && values().contains(valueOf(country2.toUpperCase()))) {
    return valueOf(country1.toUpperCase()).currency == valueOf(country2.toUpperCase()).currency
    } else return false

我在这里搜索并找到了一个我不太明白的valueOfOrNull()方法

inline fun <reified T : Enum<T>> enumValueOfOrNull(country: String): T? {
            return enumValues<T>().find { it.name == country.toUpperCase() }
        }

你能帮我解释一下这是怎么回事吗?我不知道内联的、具体化的 T: Enum 是如何工作的,它有什么作用 return。 另外,我刚刚开始学习 lambda,所以我对 .find {} 部分有一个基本的了解,但我可以使用 it

的解释

感谢大家的帮助,非常感谢。

在 Kotlin 中,inline functions get their bodies transformed in compile-time and, well, inlined at each of the call sites. While this requires more work from the compiler and leads to bigger binaries, inline functions are somewhat more flexible because, rather than compiling their bodies into one piece of bytecode for all, the compiler gets more additional information from each call site and may embed that into the inlined body, producing different results based on the calls. One example of such additional data that is embedded into the transformed inline function body is a lambda passed to the function from the call site, allowing for non-local control flow

编译器可以为特定调用站点转换正文的另一种方法是嵌入来自调用站点的实际泛型类型参数。在为所有调用点生成单个编译函数体时,编译器无法生成任何考虑实际类型参数的代码,例如 foo is T 检查。也就是说,实际的type arguments are erased. However, with inlined body for each individual call site, this becomes possible. The feature is called reified type parameters.

然后,enumValues is an intrinsic function that the compiler treats specially, which may be called on a reified type parameter that is a subtype of Enum (every enum class is), and then in the inlined function body there will be a call that returns the enum values. This is not the only intrinsic function that works with the reified type parameter during inlining: typeOf 也这样做,并生成一个 KType 标记,人们可以使用它来反省实际的类型参数。