在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
当前回答
有两种方法可以在Kotlin中应用静态
首先在类下创建一个伴生对象
为例:
class Test{
companion object{
fun isCheck(a:Int):Boolean{
if(a==0) true else false
}
}
}
你可以称这个函数为
Test.Companion.isCheck(2)
另一种方法是创建一个对象类
object Test{
fun isCheck(a:Int):Boolean{
if(a==0) true else false
}
}
编码快乐!
其他回答
您只需要创建一个伴生对象并将函数放入其中
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")
}
}
您可以通过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
简单地使用这种方法
object Foo{
fun foo() = println("Foo")
val bar ="bar"
}
Foo.INSTANCE.foo()
这对我也有用
object Bell {
@JvmStatic
fun ring() { }
}
从芬兰湾的科特林
Bell.ring()
从Java
Bell.ring()
除了迈克尔安德森的回答,我在我的项目中有其他两种编码方式。
第一:
你可以把所有变量白到一个类。 创建一个名为Const的kotlin文件
object Const {
const val FIRST_NAME_1 = "just"
const val LAST_NAME_1 = "YuMu"
}
您可以在kotlin和java代码中使用它
Log.d("stackoverflow", Const.FIRST_NAME_1)
第二:
您可以使用Kotlin的扩展函数 创建了一个名为Ext的kotlin文件,下面的代码是Ext文件中的所有代码
package pro.just.yumu
/**
* Created by lpf on 2020-03-18.
*/
const val FIRST_NAME = "just"
const val LAST_NAME = "YuMu"
你可以在kotlin代码中使用它
Log.d("stackoverflow", FIRST_NAME)
您可以在java代码中使用它
Log.d("stackoverflow", ExtKt.FIRST_NAME);