一、首先来看一下Java中的装箱和拆箱
package cn.kotliner.java.box;
/**
* Created by wangdong
* 在Java中Integer是int的包装类
* 下面两个方法是重载的不同的两个方法
* 而在Kotlin中int和Integer合二为一成Int了'
* 类型的还有Double等
*/
public interface BoxIf1 {
String get(int key);
String get(Integer key);
}
二、用kotlin来实现一中的接口
package cn.kotliner.kotlin.box
import cn.kotliner.java.box.BoxIf1
/**
* Created by wangdong
* kotlin的装箱和拆箱
*/
class BoxImpl1: BoxIf1{
//kotlin实现Java的BoxIf1接口
//两个方法因为int和Integer合并成Int,就合二为一了
override fun get(key: Int): String {
return "Hello"
}
// override fun get(key: Int?): String {
// return "Hello"
// }
}
三、看一下继承了Map接口的Java接口
package cn.kotliner.java.box;
import java.util.Map;
/**
* Created by wangdong
* 定义一个接口,继承map的接口
* 定义了两个接口方法
*/
public interface BoxIf2 extends Map<Integer, String> {
String get(int key);
String get(Integer key);
}
四、kotlin实现三接口
package cn.kotliner.kotlin.box
import cn.kotliner.java.box.BoxIf1
import cn.kotliner.java.box.BoxIf2
/**
* Created by wangdong
* 因为一个是map的get,一个是BoxIf2的get,BoxImpl2在实现他们,重载的时候他们是相互冲突的
* 所以这个是不行的
*/
class BoxImpl2: BoxIf2 {
override val size: Int
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override fun containsKey(key: Int?): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun containsValue(value: String?): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
//这个是永远都会和下一个方法冲突
override fun get(key: Int): String? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
//冲突
override operator fun get(key: Int): String? {
return "Hello"
}
override fun isEmpty(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override val entries: MutableSet<MutableMap.MutableEntry<Int, String>>
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override val keys: MutableSet<Int>
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override val values: MutableCollection<String>
get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
override fun clear() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun put(key: Int?, value: String?): String? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun putAll(from: Map<out Int, String>) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun remove(key: Int?): String? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
五、如果遇见了装箱和拆箱的问题,用Java来写,规避下就好了