是否可以通过应用参数将Kotlin KFunction1转换为KFunction0? [英] Can I convert a Kotlin KFunction1 to a KFunction0 by applying the argument?

查看:422
本文介绍了是否可以通过应用参数将Kotlin KFunction1转换为KFunction0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我引用了需要参数的函数.

I have a reference to a functionthat needs a parameter.

fun foo(x: Int) = 2 * x
val f: KFunction1<Int, Int> = ::foo

有什么办法可以写到applyArgument其中

Is there any way to write applyArgument where

val f2: KFunction0<Int> = f1.applyArgument(42) 
assertEquals("foo", f2.name)
assertEquals(84, f2())

我不想使用可调用的引用,因为我需要访问name属性.

I don't want to use a callable reference, as I need access to the name property.

推荐答案

KFunction旨在表示在Kotlin代码中明确清除的函数,但是f2在代码的任何地方均未声明.另外,KFunction具有许多反射特性和功能,与所应用的功能f2不相关.因此,即使有可能,也不建议这样做.

KFunctions are intented to represent functions that are explicitly decleared in Kotlin code, but f2 is not declared anywhere in the code. In addition KFunction has lot of reflection properties and functions which are not relevant to the applied function f2. Therefore even if it is possible it is not recommended.

如果仍然要执行此操作,则可以通过以下方式简单地编写一个applyArgument函数:

If you want to do it anyway you can simply write an applyArgument function in this way:

fun <T, R> KFunction1<T, R>.applyArgument(value: T): KFunction0<R> {
    return object : KFunction<R> by this, KFunction0<R> {
        override fun invoke(): R {
            return this@applyArgument(value)
        }
    }
}

但是,如果您需要保留名称,那么我会以一种安全的方式进行.一种方法可能是:

But, if what you need is to preserve the name, I would do it in a safe way. One way could be:

data class Named<out T>(val name: String, val value: T)

fun <T, R> Named<T>.map(transform: (T) -> R): Named<R> = Named(name, transform(value))

val <F : KFunction<*>> F.named: Named<F>
    get() = Named(name, this)

然后使用它:

fun foo(x: Int) = 2 * x
val f: Named<(Int) -> Int> = ::foo.named

val f2: Named<() -> Int> = f.map { fValue -> { fValue(42) } }
assertEquals("foo", f2.name)
assertEquals(84, f2.value())

这篇关于是否可以通过应用参数将Kotlin KFunction1转换为KFunction0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆