```operatorfun Pointer.get(i: Int): Int {returnwhen(i) {0-> x1-> yelse->throwIndexOutOfBoundsException("Invalid params: $i") } } ``` 这个get方法,参数可以是任意类型,比如:map;也可以定义具有多个参数的get方法; 例子 ```operatorfun MutablePointer.set(index: Int,value: Int) {when(index...
operator fun Point.set(index: Int, value: Int) { when(index) {0 -> x =value1 -> y =valueelse->throwIndexOutOfBoundsException("out") } } val p= Point(10, 20) p[1] = 30//这里其实调用的是上面扩展函数的setprintln(p[1])//这里调用的是上面扩展函数的get,打印的结果是30 如上是增...
repeat():String类中将字符串重复n遍的函数 operator fun String.times(n:Int)= repeat(n) fun getRandomLength(str: String) = str*(1..20).random() 1. 2. 3.
invoke约定 和上面的get约定一样,[] 就是调用 get 方法的更简洁的方式,这里有个invoke约定,它的作用就是让对象像函数一样调用方法,下面直接来个例子: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 dataclassTestBean(val name:String,val age:Int){//重载定义invoke方法operator funinvoke():String{retur...
和上面的get约定一样,[] 就是调用 get 方法的更简洁的方式,这里有个invoke约定,它的作用就是让对象像函数一样调用方法,下面直接来个例子: data class TestBean(val name: String,val age: Int){ //重载定义invoke方法 operator fun invoke() : String{ ...
get操作符则是通过[]来实现的 例如下方ElementOperator定义了get、minus、plus三个操作符,在main函数中对element对象进行-、[]、+的操作,对应着ElementOperator中所定义的操作符: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 interface ElementOperator { var nameList: ArrayList<String> operator fun get(s...
operator 将⼀个函数标记为重载⼀个操作符或者实现⼀个约定 out 将类型参数标记为协变 override 将⼀个成员标记为超类成员的覆盖 private 将⼀个声明标记为在当前类或⽂件中可⻅ protected 将⼀个声明标记为在当前类及其⼦类中可⻅ public 将⼀个声明标记为在任何地⽅可⻅ reified ...
operatorfunString.times(int:Int)=repeat(int) 1. 因此刚才的 getRandomLenthString()函数可以使用这种写法了: fungetRandomLenthString(str:String)=str*(1..20).random() 1.
该类需要包含 getValue() 方法和 setValue() 方法,且参数 thisRef 为进行委托的类的对象,prop 为进行委托的属性的对象。 importkotlin.reflect.KProperty// 定义包含属性委托的类classExample{varp: StringbyDelegate() }// 委托的类classDelegate{operatorfungetValue(thisRef:Any?, property:KProperty<*>): Stri...
该类需要包含 getValue() 方法和 setValue() 方法,且参数 thisRef 为进行委托的类的对象,prop 为进行委托的属性的对象。 importkotlin.reflect.KProperty// 定义包含属性委托的类classExample{varp:StringbyDelegate()}// 委托的类classDelegate{operatorfun getValue(thisRef:Any?,property:KProperty<*>):String{...