属性设置器的方法参考 [英] Method reference to property setter

查看:85
本文介绍了属性设置器的方法参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用kotlin-reflect的情况下获得对属性设置器的方法引用?

How could I get method reference to property setter without using kotlin-reflect?

基本上,如果我用Java方式编写代码,那就超级简单

Basically, if I'll write my code in java way it's super simple

fun setValue(i: Int) = Unit
val a: (Int) -> Unit = this::setValue

但是对于var value: Int我要得到

var value = 1
val a: KMutableProperty0<Int> = this::value

推荐答案

this::value是属性引用.它返回一个KMutableProperty.要获取设置器,您将需要KMutablePropertysetter字段.因此,您将需要以下内容:

this::value is a property reference. It returns a KMutableProperty. To get the setter you will need the setter field of KMutableProperty. So you will need this:

class C {
    var field: Int = 1
    fun getFieldSetter(): (Int) -> Unit{
        return this::field.setter
    }
}

这篇关于属性设置器的方法参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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