是否可以通过类型转换来满足Kotlin中的多种类型约束?
假设我遇到以下情况,但想避免将类型强制转换为类C(以防多个类实现A和B,或者我不知道type C):
interface A
interface B
class C: A, B
fun <T> foo(bar: T) where T: A, T: B {
}
Run Code Online (Sandbox Code Playgroud)
是否有可能强制转换A和B同步?聪明的演员似乎不允许这样做。我可以手动投射吗?
val c = C()
foo(c) // works
val d: Any = c
if (d is A && d is B) {
foo(d) // smart cast doesn't work here, compiler error
}
// Something like this maybe?
foo(d as A && B)
Run Code Online (Sandbox Code Playgroud)
我知道可以通过创建一个同时继承自A和的新接口,B然后使用该接口来实现,但是如果我不控制所讨论的类,则可能无法实现。 …
kotlin ×1