常量
Java中:
class StaticDemoActivity {
public static final String LOAN_TYPE = "loanType";
public static final String LOAN_TITLE = "loanTitle";
}
Kotlin中:
class StaticDemoActivity {
companion object {
val LOAN_TYPE = "loanType"
val LOAN_TITLE = "loanTitle"
}
}
或者
class StaticDemoActivity {
companion object StaticParams{
val LOAN_TYPE = "loanType"
val LOAN_TITLE = "loanTitle"
}
}
或者
class StaticDemoActivity {
companion object {
const val LOAN_TYPE = "loanType"
const val LOAN_TITLE = "loanTitle"
}
}
注:
const
关键字用来修饰常量,且只能修饰val
,不能修饰var
,companion object
的名字可以省略,可以使用Companion
来指代
引用常量(这里的引用只针对于java引用kotlin代码)
TestEntity类引用StaticDemoActivity中的常量
class TestEntity {
public TestEntity () {
String title = StaticDemoActivity.Companion.getLOAN_TITLE();
}
}
或者
class TestEntity {
public TestEntity () {
String title = StaticDemoActivity.StaticParams.getLOAN_TITLE();
}
}
或者
class TestEntity {
public TestEntity () {
String title = StaticDemoActivity.LOAN_TITLE;
String type= StaticDemoActivity.LOAN_TYPE;
}
}
静态方法
Java代码:
class StaticDemoActivity {
public static void test(){
、、、
}
}
Kotlin中:
class StaticDemoActivity {
companion object {
fun test(){
、、、
}
}
}
或者
class StaticDemoActivity {
companion object StaticParams{
fun test() {
、、、
}
}
}
引用静态方法(这里的引用只针对于java引用kotlin代码)
TestEntity类引用StaticDemoActivity中的静态方法
class TestEntity {
public TestEntity () {
StaticDemoActivity.Companion.test();
}
}
或者
class TestEntity {
public TestEntity () {
StaticDemoActivity.StaticParams.test();
}
}
companion object {}
中用来修饰静态常量
,或者静态方法
,单例
等等
推荐文章:
Kotlin中的object 与companion object的区别
最后,希望此篇博客对大家有所帮助,欢迎提出问题及建议共同探讨,如有兴趣可以关注我的博客,谢谢!