文章目录
前言
kotlin的var,val,const的区别网上有很多的文章了,但是这些关键字在companion object和top-level情况下的多种情况又是怎么样的?本文通过编译成Java代码来探讨
kotlin类中var val const编译情况
class MyTest{
var test0: String = "aaa"
// 编译后:private String test0 = "aaa";
@JvmField var test1: String = "aaa"
// 编译后:public String test1 = "aaa";
val test2:String = "aaa"
// 编译后:private final String test2 = "aaa";
@JvmField val test3:String = "aaa"
// 编译后:public final String test3 = "aaa";
}
kotlin companion object 中var val const编译情况
class MyTest{
companion object{
var test4:String = "aaa"
// 编译后:private static String test4 = "aaa";
@JvmField var test5:String = "aaa"
// 编译后:public static String test5 = "aaa";
val test6:String = "aaa"
// 编译后:private static final String test6 = "aaa";
@JvmField val test7: String = "aaa"
// 编译后:public static final String test7 = "aaa";
const val test8:String = "aaa"
// 编译后:public static final String test8 = "aaa";
}
}
kotlin top-level 中var val const编译情况
var test9: String = "aaa"
// 编译后: private static String test9 = "aaa";
@JvmField var test10: String = "aaa"
// 编译后: public static String test10 = "aaa";
val test11: String = "aaa"
// 编译后: private static final String test11 = "aaa";
@JvmField val test12: String = "aaa"
// 编译后: public static final String test12 = "aaa";
const val test13:String = "aaa"
// 编译后: public static final String test13 = "aaa";
以上是var val const val在companion object,top-level情况下编译结果。
对于以上的结果,可以总结下:
- var:被private修饰,提供public的setter和getter相关方法
- val:被private final修饰,提供public的getter相关方法
- const val:被public static final修饰(只能用于top-level,object和companion object)
- companion object,object和top-level:加上static修饰
- @JvmField:加上public修饰