一、匿名对象表达式
/**
* DESC : 匿名对象表达式
*
* 总结: java接口有两种实现方式,Kotlin只有一种object: KtRunnable的方式
*/
const val KtBaseObjectTest03_TAG = "KtBaseObjectTest03"
open class KtBaseObject {
open fun add(info : String) {
Log.d(KtBaseObjectTest03_TAG, "KtBaseObject...add==>info="+info)
}
open fun del(info : String) {
Log.d(KtBaseObjectTest03_TAG, "KtBaseObject...del==>info="+info)
}
}
/**
* 具名对象实现,创建子类KtBaseObjectImpl
*
*/
class KtBaseObjectImpl : KtBaseObject() {
override fun add(info: String) {
Log.d(KtBaseObjectTest03_TAG, "KtBaseObject子类...add==>info="+info)
}
override fun del(info: String) {
Log.d(KtBaseObjectTest03_TAG, "KtBaseObject子类...del==>info="+info)
}
}
/**
* 定义kotlin中的KtRunnable接口,类似于java中的Runnable接口,用于区分用法的不同
*/
interface KtRunnable {
fun run()
}
class KtBaseObjectTest03 {
/**
* 匿名对象表达式
*/
fun testNestedObject01() {
//匿名对象 表达式方式
val ktbaseObj /*: KtBaseObject */= object : KtBaseObject() {
override fun add(info: String) {
Log.d(KtBaseObjectTest03_TAG, "KtBaseObject匿名对象...add==>info="+info)
}
override fun del(info: String) {
Log.d(KtBaseObjectTest03_TAG, "KtBaseObject匿名对象...del==>info="+info)
}
}
ktbaseObj.add("hello lanny")
ktbaseObj.del("hello lanny")
}
/**
* 具名对象
*/
fun testNestedObject02() {
//创建具名对象ktBaseObjectImpl
val ktBaseObjectImpl = KtBaseObjectImpl()
ktBaseObjectImpl.add("具名对象实现")
ktBaseObjectImpl.del("具名对象实现")
}
/**
* 对java的接口Runnable,用Kt的匿名对象表达式实现
*/
fun testNestedObject03() {
val runnable = object : Runnable {
override fun run() {
Log.d(KtBaseObjectTest03_TAG, "testNestedObject03==>run...kotlin匿名对象方式")
}
}
runnable.run()
}
/**
* 对java的接口Runnable, 用java的最简洁的方式实现
*/
fun testNestedObject04() {
val runnable = Runnable {
Log.d(KtBaseObjectTest03_TAG, "testNestedObject04==>run...java简洁方式实现")
}
runnable.run()
}
/**
* 对kotlin的接口KtRunnable,可以使用匿名对象表达式实现
*/
fun testNestedObject05() {
val runnable = object : KtRunnable {
override fun run() {
Log.d(KtBaseObjectTest03_TAG, "testNestedObject05==>run...kotlin接口实现匿名对象")
}
}
runnable.run()
}
/**
* KT方式不能像java一样使用简洁的方式去实现,以下代码会报错
*/
fun testNestedObject06() {
/*val runnable = KtRunnable {
Log.d(KtBaseObjectTest03_TAG, "testNestedObject06==>run...kotlin简洁方式实现,会出错哦")
}
runnable.run()*/
}
}
网友评论