问题描述
如果我定义
class MyF : KFunction0<Int> {
override val name: String = "f"
override fun invoke() = 42
override val annotations: List<Annotation>
get() = TODO()
....
}
我会写
val f0: KFunction0<Int> = MyF()
assertEquals("f", f0.name)
但如果我尝试
assertEquals(42, f0())
我得到java.lang.ClassCastException: MyF cannot be cast to kotlin.jvm.functions.Function0
如何定义自己的KFunction0
实现?
我不能使用() -> Int
,因为我需要name
属性.
I can't work with () -> Int
because I need the name
property.
我正在使用Kotlin 1.3.21.
I'm using Kotlin 1.3.21.
另外-看来我可以跑步
val f02 = MyF()
assertEquals(42, f02())
我的实际用例是
推荐答案
从Kotlin JVM显式实现内部类绝对不是一个好主意.由于某种原因,您在IntelliJ或Android Studio中没有该类的代码完成
It is definitely not a good idea to explicitly implement an internal class from Kotlin JVM. You do not have code completion for that classes in IntelliJ or Android Studio for a reason
您可以改用可调用的引用,以使Kotlin编译器为您生成所有必需的类. https://kotlinlang.org/docs/reference/reflection.html#callable-引用
You may use callable references instead, to make Kotlin compiler generate all necessary classes for you.https://kotlinlang.org/docs/reference/reflection.html#callable-references
fun myfun() = 42
val kFunction = ::myfun
println(kFunction.name)
println(kFunction())
好处-将来的Kotlin版本不太可能破坏该代码(并可能破坏您的继承者类)
The benefit - future version of Kotlin will unlikely to break that code (and may break you inheritor class)
如果您需要一个更长的名称,可以这样声明
Should you need a longer name for the function, you may declare it like that
fun `my function with long name`() = 43
这篇关于如何在Kotlin中实现KFunctionN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!