public final class Hello { public static final Hello INSTANCE; public final int getAge(); public final void sayHello(); static {}; }
kotlin伴生对象
1 2 3 4 5 6 7 8 9 10 11
class Hello4 { var age : Int = 0 get() {return field}
companion object { fun test(): Unit{
} } }
1 2 3 4 5 6 7 8 9 10
伴生对象字节码揭秘
public final class Hello4 { public static final Hello4$Companion Companion; public Hello4(); public final int getAge(); public final void setAge(int); static {}; }
kotlin扩展函数
1
fun Hello.sayBey() = print("bey")
扩展函数回在声明了当前扩展函数的类中添加一个新的static函数,把被扩展的class当做参数传入
1 2
字节码揭秘: public static final void sayBey(Hello);
kotlin 内部类和嵌套类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Outer {
var name : String = "zhangsan" class Nested { fun test() { } }
inner class Inner { fun test() { this@Outer.name } } }
看调用
1 2 3 4
fun main() { Outer.Nested().test() Outer().Inner().test() }
数据对象: data object DataObj { lateinit var name : String } 对应字节码: public final class DataObj { public static final DataObj INSTANCE; public static java.lang.String name; public final java.lang.String getName(); public final void setName(java.lang.String); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); static {}; }
数据对象在字节码底部会声明当前object的实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14
数据类: 至少有一个构建参数 data class DataClazz(val name: String) 数据类字节码: public final class DataClazz { public DataClazz(java.lang.String); public final java.lang.String getName(); public final java.lang.String component1(); public final DataClazz copy(java.lang.String); public static DataClazz copy$default(DataClazz, java.lang.String, int, java.lang.Object); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); }
kotlin类委托
1 2 3 4 5 6 7 8 9 10 11 12 13 14
interface ImageLoader{ fun load(url: String) } class FresoLoader : ImageLoader { override fun load(url: String) { println("load $url with freso") } } class ImageLoaderEngine(imageLoader: ImageLoader) : ImageLoader by imageLoader
fun main() { val engine = ImageLoaderEngine(FresoLoader()) engine.load("http:xx.png") }