作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
在以下代码中,“万圣节快乐!”
、42
等被标记为“类型不匹配”。 (必需:T,找到:String(或 Int))但编译器不应该能够从类型检查中推断出返回值是正确的类型吗?
interface Type<T>
class StringType() : Type<String>
class IntType1() : Type<Int>
class IntType2(val a: Int, val b: Int) : Type<Int>
fun <T> something(type: Type<T>): T = when (type) {
is StringType -> "Happy Halloween!"
is IntType1 -> 42
is IntType2 -> type.a * type.a + type.b * type.b + type.a * type.b
else -> throw IllegalArgumentException()
}
最佳答案
你可以这样写:
interface Type<T>
class StringType() : Type<String>
class IntType1() : Type<Int>
class IntType2(val a: Int, val b: Int) : Type<Int>
inline fun <reified T> something(type: Type<T>): T {
val result = when(type) {
is StringType -> "Happy Halloween"
is IntType1 -> 42
is IntType2 -> type.a * type.a + type.b * type.b + type.a * type.b
else -> throw IllegalArgumentException()
}
return if (result is T) result else throw Exception()
}
运行以下:
fun main(args: Array<String>) {
println(something(StringType()))
println(something(IntType1()))
println(something(IntType2(2, 3)))
}
会给你这个输出:
Happy Halloween
42
19
在此处了解有关内联函数和具体参数的更多信息:Reified type parameters .
关于kotlin - 为什么在尝试为已检查的泛型参数返回值时会出现类型不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40351071/
我是一名优秀的程序员,十分优秀!