gpt4 book ai didi

casting - 在 Kotlin 中可以进行交叉转换吗?

转载 作者:IT老高 更新时间:2023-10-28 13:40:25 27 4
gpt4 key购买 nike

我在 Java 中有这样的方法:

public <T extends A & B> methodName(T arg, ...)

其中 A 是一个类,B 是一个接口(interface)。

在我的 kotlin 类中,我有另一个 C 类型的 variable,我希望实现以下目标:

if (variable is A && variable is B) {
methodName(variable, ...)
} else {
// do something else
}

是否可以正确地转换 variable 以便它可以用作参数而不会出错?

Currently, the variable has a setter method, so smart casting isn't available. However, I have also tested it with a local val and the value is inferred to have type Any which doesn't help.

最佳答案

Kotlin 不支持交集类型。这会导致 variable要聪明地投到Any , 因为那是 A 的共同祖先和 B .

不过,Kotlin 确实支持泛型类型约束。您可以使用它来将类型参数限制为一种或多种类型。这可以用于方法和类。这是函数的语法(相当于 Kotlin 中的 methodName):

fun <T> methodName(arg: T)
where T : A,
T : B {
....
}

您可以通过创建一个扩展两个 A 的类来使用它来解决您的问题。和 B ,然后将这些类型的实现委托(delegate)给您的对象。像这样:

class AandB<T>(val t: T) : A by t, B by t
where T : A,
T : B

您现在可以调用methodName通过更改您的 if-test 来检查它是否是 AandB<*> :

if (variable is AandB<*>) {
methodName(variable, ...)
}

您确实需要包装 variableAandB虽然在某个地方。如果您没有 variable 的类型信息,我认为您无法做到这一点。随处可用。

注意:AandB类未实现 hashCode , equalstoString .您可以实现它们以委托(delegate)给 t的实现。

注意 2:这仅适用于 AB是接口(interface)。你不能委派给一个类(class)。

关于casting - 在 Kotlin 中可以进行交叉转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44448651/

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