val y: Int) { // 定义一个名为 plus 的方法 operator fu
}classDelegate {operatorfun getValue(thisRef: Any?, property: KProperty<*>): String {//获取属性值的实际实现return"Delegated value"}operatorfun setValue(thisRef: Any?, property: KProperty<*>, value: String) {//设置属性值的实际实现println("Setting value to: $value") } } 在上面的代码中,E...
AI代码解释 importkotlin.reflect.KPropertyclassCustomDelegate{privatevarvalue:String=""operator fungetValue(thisRef:Any?,property:KProperty<*>):String{println("Getting value: $value")returnvalue}operator funsetValue(thisRef:Any?,property:KProperty<*>,newValue:String){println("Setting value: $newValue"...
operatorfunPoint.get(index:Int):Int{returnwhen(index){0->x1->yelse->throwIndexOutOfBoundsException(“Invalidcoordinate$index")}}>>> val p = Point(10,20)>>> println(p[1]) 只需要定义一个名为get的函数,并标记operator. 向p[1]这样将被转换为get方法的调用. x[a,b]->x.get(a,b) 注意,...
用operator 关键字声明 plus 函数,可以直接使用 + 号来做运算,使用 operator 修饰符声明 minus 函数,可以直接使用 - 号来做运算,其实我们也可以在自定义类里面实现 plus (+) 和 minus (-) 做运算。 data class Salary(var base: Int = 100){
该类需要包含 getValue() 方法和 setValue() 方法,且参数 thisRef 为进行委托的类的对象,prop 为进行委托的属性的对象。 importkotlin.reflect.KProperty// 定义包含属性委托的类classExample{varp:StringbyDelegate()}// 委托的类classDelegate{operatorfun getValue(thisRef:Any?,property:KProperty<*>):String{...
{property.name} 属性"}operatorfunsetValue(thisRef:Any?,property:KProperty<*>,value:String){println("$thisRef 的 ${property.name} 属性赋值为 $value")}}funmain(args:Array<String>){vale=Example()println(e.p)// 访问该属性,调用 getValue() 函数e.p="Runoob"// 调用 setValue() 函数println...
上面代码冗余,所谓委托类,就是一个包含getValue和setValue函数的类,这两个函数operator声明 在使用委托类时,需要by关键字,创建委托类实例的代码放在by后面 如下 import kotlin.reflect.KProperty fun main(arg: Array<String>) { val myClass1=myClass1() ...
/** * 使用 by 关键字连接了左边的 p 属性和右边的 Delegate 实例 * 这种写法就代表着将 p 属性的具体实现委托给了 Delegate 去完成 */ class MyClass{ var p by Delegate() } /** * 下面是一个被委托类的代码实现模版 * 一、getValue 方法和setValue 方法必须使用 operator 关键字修饰 * * 二、ge...
2、是否每次我们更改 field 属性引用都会调用 setValue 方法 (答案:yes) 代码太多,截图已经放不下了,上代码吧 运行完代码会放出上面两条结论的验证 class EnTrustObject {var field: Resource by ResourceDelete()}class ResourceDelete {var resource: Resource = Resource("初始的对象")operator fun getValue(enT...