Kotlin是否可以进行路口铸造? [英] Is intersection casting possible in Kotlin?

查看:87
本文介绍了Kotlin是否可以进行路口铸造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有一个像这样的方法:

I have a method in Java like so:

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

其中A是一个类,B是一个接口.

where A is a class and B is an interface.

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

In my kotlin class, I have another variable of type C, and I wish to achieve the following:

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

是否可以正确地转换variable以便可以将其用作无错误的参数?

Is it possible to properly cast variable so that it may be used as an argument without errors?

当前,variable具有setter方法,因此无法进行智能投射 可用的.但是,我也使用本地val和 值被推断为没有帮助的Any类型.

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.

推荐答案

科特林不支持交叉点类型.这导致variable被智能地强制转换为Any,因为这是AB的共同祖先.

Kotlin does not support intersection types. This causes variable to be smart cast to Any, because that is the common ancestor of A and B.

但是,Kotlin确实支持泛型类型约束.您可以使用它来将类型参数限制为一个或多个类型.这可以在方法和类上使用.这是函数的语法(等同于您在Kotlin中的methodName):

However, Kotlin does support generic type constraints. You can use this to constrain a type parameter to one or more types. This can be used on both methods and classes. This is the syntax for functions (the equivalent of your methodName in Kotlin):

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

您可以使用此方法来创建一个扩展AB的类,然后将这些类型的实现委派给您的对象,以解决您的问题.像这样:

You can use this to get around your problem by creating a class which extends both A and B, and then delegates the implementation of these types to your object. Like this:

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

您现在可以通过更改if-test来检查其是否为AandB<*>:

You can now call methodName by changing your if-test to check if it is a AandB<*>:

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

您确实需要将variable包裹在AandB中的某个位置.如果您在任何地方都没有variable的类型信息,我认为您无法做到.

You do need to wrap variable in a AandB somewhere though. I don't think you can do it if you don't have the type information for variable available anywhere.

注意:AandB类未实现hashCodeequalstoString.您可以实现它们以委派给t的实现.

Note: The AandB class does not implement hashCode, equals or toString. You could implement them to delegate to t's implementation.

注2:仅当AB是接口时,此方法才有效.您不能委托给班级.

Note 2: This only works if A and B are interfaces. You can not delegate to a class.

这篇关于Kotlin是否可以进行路口铸造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆