在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
当前回答
我想对以上的回答做一些补充。
是的,你可以在源代码文件中定义函数(在类之外)。但是如果使用Companion Object在类中定义静态函数会更好,因为您可以通过利用Kotlin Extensions添加更多静态函数。
class MyClass {
companion object {
//define static functions here
}
}
//Adding new static function
fun MyClass.Companion.newStaticFunction() {
// ...
}
你可以调用上面定义的函数,就像你调用伴侣对象中的任何函数一样。
其他回答
您只需要创建一个伴生对象并将函数放入其中
class UtilClass {
companion object {
// @JvmStatic
fun repeatIt5Times(str: String): String = str.repeat(5)
}
}
从kotlin类中调用该方法:
class KotlinClass{
fun main(args : Array<String>) {
UtilClass.repeatIt5Times("Hello")
}
}
或使用import
import Packagename.UtilClass.Companion.repeatIt5Times
class KotlinClass{
fun main(args : Array<String>) {
repeatIt5Times("Hello")
}
}
从java类中调用该方法:
class JavaClass{
public static void main(String [] args){
UtilClass.Companion.repeatIt5Times("Hello");
}
}
或者在方法中添加@JvmStatic注释
class JavaClass{
public static void main(String [] args){
UtilClass.repeatIt5Times("Hello")
}
}
或者在方法中添加@JvmStatic注释并在java中进行静态导入
import static Packagename.UtilClass.repeatIt5Times
class JavaClass{
public static void main(String [] args){
repeatIt5Times("Hello")
}
}
这对我也有用
object Bell {
@JvmStatic
fun ring() { }
}
从芬兰湾的科特林
Bell.ring()
从Java
Bell.ring()
所有静态成员和函数都应该在伴生块中
companion object {
@JvmStatic
fun main(args: Array<String>) {
}
fun staticMethod() {
}
}
让,你有一个班级学生。你有一个静态方法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
您可以通过Companion Objects在Kotlin中实现静态功能
Adding companion to the object declaration allows for adding the static functionality to an object even though the actual static concept does not exist in Kotlin. A companion object can access all members of the class too, including the private constructors. A companion object is initialized when the class is instantiated. A companion object cannot be declared outside the class. class MyClass{ companion object { val staticField = "This is an example of static field Object Decleration" fun getStaticFunction(): String { return "This is example of static function for Object Decleration" } } }
伴侣对象的成员可以通过简单地使用类名作为限定符来调用:
输出:
MyClass.staticField // This is an example of static field Object Decleration
MyClass.getStaticFunction() : // This is an example of static function for Object Decleration