Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 类型转换以满足多个类型约束_Kotlin - Fatal编程技术网

Kotlin 类型转换以满足多个类型约束

Kotlin 类型转换以满足多个类型约束,kotlin,Kotlin,在kotlin中是否可以通过类型转换来满足多个类型约束 假设我有以下情况,但希望避免类型转换到类C(如果多个类实现A和B,或者我不知道类型C): 我知道可以创建一个新接口来继承a和B,然后使用它,但如果我不控制所讨论的类,这可能是不可能的 感谢该类型必须明确实现所需的接口,并且由于任何不能同时是B和A(即使它同时实现了两者),因此必须有第三种类型,如C 这个类似的问题有一个通用的解决方法 因此,实现A和B的任意类型T可以被识别为是这样的,但是是和as不能直接与&组合,这使得在没有明确实现包装器的

在kotlin中是否可以通过类型转换来满足多个类型约束

假设我有以下情况,但希望避免类型转换到类
C
(如果多个类实现
A
B
,或者我不知道类型
C
):

我知道可以创建一个新接口来继承
a
B
,然后使用它,但如果我不控制所讨论的类,这可能是不可能的


感谢

该类型必须明确实现所需的接口,并且由于
任何
不能同时是
B
A
(即使它同时实现了两者),因此必须有第三种类型,如
C

这个类似的问题有一个通用的解决方法

因此,实现
A
B
的任意类型
T
可以被识别为是这样的,但是
as
不能直接与
&
组合,这使得在没有明确实现包装器的情况下不可能满足函数类型约束

interface A
interface B

class C: A, B

fun <T> foo(bar: T) where T: A, T: 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)