【发布时间】:2019-04-08 11:24:45
【问题描述】:
我在 Kotlin 中遇到了函数参数的问题。我将在一些代码的帮助下解释这个问题。
我创建了一个类层次结构。当我将子类型传递给需要父类型的函数时,没有问题。
open class A (val i: Int)
class B (val j: Int) : A(j)
fun f(x: A){
print(x)
}
fun test_f(){
f(A(1))
f(B(1)) //no problem
}
我试图用函数参数来模仿这个。
fun g(x: (A)->Int){
print(x)
}
fun test_g(){
val l1 = { a: A -> a.hashCode()}
g(l1)
val l2 = { b: B -> b.hashCode()}
g(l2) //Error: Type mismatch. Required: (A)->Int, Found: (B)->Int
}
函数类型(B) -> Int 似乎不是(A) -> Int 的子类型。
解决此问题的最佳方法是什么?
我原来的问题是在A.h 中定义一个高阶函数,它以函数z: (A) -> X 作为参数。我想在B 类型的对象上调用h 并传递一个函数z: (B) -> X。
更新: 我尝试了具有上限的泛型,但我的问题没有解决。请在下面找到代码:
// Using generics doesn't allow me to pass A.
open class A (val i: Int) {
fun <M: A> g(x: (M)->Int){
print(x(this)) // Error: Type mismatch. Expected: M, Found: A
}
}
【问题讨论】:
标签: kotlin