我目前正在开发一个需要委托函数变量的应用程序.我在try 这样做时遇到了一些问题.以下是一个最小的可重复示例的代码:
package org.prismsus.tank
import kotlin.reflect.KProperty
fun addFunc(a : Int, b : Int) : Int {
return a + b
}
class Test{
inner class PrintFuncCall1{
operator fun getValue(thisRef: Any?, property: KProperty<*>): (Int, Int) -> Int {
fun temp(a : Int, b : Int) : Int {
println("Function ${property.name}")
return addFunc(a, b)
}
return ::temp
}
}
val delegatedFun1 : (Int, Int) -> Int by PrintFuncCall1()
inner class PrintFuncCall2<F : (Array<out Any>) -> R, R>{
operator fun getValue(thisRef : Any?, property : KProperty<*>) : (Array<out Any>) -> R{
fun temp(vararg params : Any) : R{
println("Function ${property.name}")
println("Params: ${params.joinToString()}")
return addFunc(params[0] as Int, params[1] as Int) as R
}
return ::temp
}
}
val delegatedFun2 : (Int, Int) -> Int by PrintFuncCall2()
}
fun main(){
val test = Test()
println(test.delegatedFun1(1, 2))
println(test.delegatedFun2(3, 4))
}
在这里,delegatedFun1
和PrintFuncCall1
工作得很好.然而,我try 将委托类修改为通用类,发现这不起作用.具体来说,我遇到了delegatedFun2
和PrintFuncCall2
的编译错误:
Property delegate must have a 'getValue(Test, KProperty<*>)' method. None of the following functions is suitable:
public final operator fun getValue(thisRef: Any?, property: KProperty<*>): (Array<out Any>) -> ??? defined in org.prismsus.tank.Test.PrintFuncCall2
我不太明白为什么getValue
需要thisRef
才是类型Test
,这是更大类别的类型.这尤其奇怪,因为我正在委托(Int, Int) -> Int
类型的变量.此外,即使我try 将getValue
的签名更改为getValue(thisRef : Test, property : KProperty<*>)
,我也会出现以下错误:
Property delegate must have a 'getValue(Test, KProperty<*>)' method. None of the following functions is suitable:
public final operator fun getValue(thisRef: Test, property: KProperty<*>): (Array<out Any>) -> ??? defined in org.prismsus.tank.Test.PrintFuncCall2
除此之外,我还有一个小问题是Kotlin对类型参数的约束机制.我对PrintFuncCall2
的目的是将F
标记为函数的类型,并将R
标记为函数F
的返回值.然而,当将getValue
的签名从getValue(thisRef : Test, property : KProperty<*>) : (Array<out Any>) -> R
更改为getValue(thisRef : Test, property : KProperty<*>) : F
时,我在第return ::temp
行收到了IDE的这条消息:
Required:
KFunction1<Array<out Any>, R>
Found:
F
这两个不应该是一回事吗?