kotlin 解构函数声明和运算符重载operator
2022-11-12 本文已影响0人
Bfmall
kt的解构函数声明和运算符重载operator学习笔记###
/**
* DESC : kt的解构函数声明和运算符重载operator
*/
const val KtBaseObjectTest07_TAG = "KtBaseObjectTest07"
class TeacherBean(var name: String, var age : Int, var info : String) {
/**
* 注意:component的顺序必须和参数一一对应,从component1开始到2,3.......
* 函数声明为operator类型
*/
operator fun component1() = name
operator fun component2() = age
operator fun component3() = info
}
data class TeacherBean2(var name: String, var age : Int, var info : String)
/**
* 为了方便测试,使用data class, 使用toString方法打印
* 测试运算符重载
*/
data class ProductInfo(val price1: Int, val price2: Int) {
operator fun plus(otherProductInfo: ProductInfo) : ProductInfo {
return ProductInfo(price1 + otherProductInfo.price1, price2 + otherProductInfo.price2)
}
}
class KtBaseObjectTest07 {
fun testComponent01() {
//testComponent01==>com.xyaty.kotlinbasedemo.base05.TeacherBean@9381bfb
Log.d(KtBaseObjectTest07_TAG, "testComponent01==>"+TeacherBean("张三", 30, "english"))
//testComponent01==>TeacherBean2(name=李四, age=31, info=china)
Log.d(KtBaseObjectTest07_TAG, "testComponent01==>"+TeacherBean2("李四", 31, "china"))
/**
* 如果不加operator,使用下面的解构代码会出错
* operator fun component1() = name
*/
val(name, age, info) = TeacherBean("laowang", 50, "游民")
//testComponent01==>解构...name=laowang, age=50, info=游民
Log.d(KtBaseObjectTest07_TAG, "testComponent01==>解构...name="+name
+", age="+age+", info="+info)
val(name2, age2, _) = TeacherBean2("laowang", 50, "老王信息不接收")
//testComponent01==>解构...name2=laowang, age2=50
Log.d(KtBaseObjectTest07_TAG, "testComponent01==>解构...name2="+name2
+", age2="+age2)
}
/**
* 运算符重载
*/
fun testOperator01() {
val p1 = ProductInfo(20, 200)
val p2 = ProductInfo(30, 300)
val p3 = p1.plus(p2)
//testOperator01==>ProductInfo(price1=50, price2=500)
Log.d(KtBaseObjectTest07_TAG, "testOperator01==>"+p3)
}
}