在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
当前回答
这对我也有用
object Bell {
@JvmStatic
fun ring() { }
}
从芬兰湾的科特林
Bell.ring()
从Java
Bell.ring()
其他回答
让,你有一个班级学生。你有一个静态方法getUniversityName()和一个静态字段totalStudent。
你应该在你的类中声明同伴对象块。
companion object {
// define static method & field here.
}
然后你的类看起来像
class Student(var name: String, var city: String, var rollNumber: Double = 0.0) {
// use companion object structure
companion object {
// below method will work as static method
fun getUniversityName(): String = "MBSTU"
// below field will work as static field
var totalStudent = 30
}
}
然后你可以像这样使用那些静态方法和字段。
println("University : " + Student.getUniversityName() + ", Total Student: " + Student.totalStudent)
// Output:
// University : MBSTU, Total Student: 30
简单来说,你可以使用“同伴对象”进入Kotlin静态世界,比如:
companion object {
const val TAG = "tHomeFragment"
fun newInstance() = HomeFragment()
}
要创建一个常量字段,请使用代码中的“const val”。 但是尽量避免使用静态类,因为它会给使用Mockito进行单元测试带来困难。
Kotlin没有任何静态关键字。您可以在Java和Kotlin中使用下面的代码
object AppHelper {
@JvmStatic
fun getAge() : Int = 30
}
Java类调用
AppHelper.getAge();
呼叫Kotlin类
AppHelper.getAge()
它非常适合我。谢谢
简单地使用这种方法
object Foo{
fun foo() = println("Foo")
val bar ="bar"
}
Foo.INSTANCE.foo()
java静态方法到kotlin等效方法的确切转换如下所示。例:这里util类有一个静态方法,它在java和kotlin中都是等效的。@JvmStatic的使用非常重要。
Java代码:
class Util{
public static String capitalize(String text){
return text.toUpperCase();}
}
芬兰湾的科特林代码:
class Util {
companion object {
@JvmStatic
fun capitalize(text:String): String {
return text.toUpperCase()
}
}
}