在Kotlin中没有静态关键字。

在Kotlin中表示静态Java方法的最佳方法是什么?


当前回答

所有静态成员和函数都应该在伴生块中

  companion object {
    @JvmStatic
    fun main(args: Array<String>) {
    }

    fun staticMethod() {
    }
  }

其他回答

Kotlin没有任何静态关键字。您可以在Java和Kotlin中使用下面的代码

 object AppHelper {
    @JvmStatic
    fun getAge() : Int = 30
}

Java类调用

AppHelper.getAge();

呼叫Kotlin类

AppHelper.getAge()

它非常适合我。谢谢

您只需要创建一个伴生对象并将函数放入其中

  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")
   }
}

简单来说,你可以使用“同伴对象”进入Kotlin静态世界,比如:

  companion object {
    const val TAG = "tHomeFragment"
    fun newInstance() = HomeFragment()
}

要创建一个常量字段,请使用代码中的“const val”。 但是尽量避免使用静态类,因为它会给使用Mockito进行单元测试带来困难。

很多人提到伴生对象,这是正确的。但是,正如你所知道的,你也可以使用任何类型的对象(使用对象关键字,而不是类),即,

object StringUtils {
    fun toUpper(s: String) : String { ... }
}

像使用java中的静态方法一样使用它:

StringUtils.toUpper("foobar")

That sort of pattern is kind of useless in Kotlin though, one of its strengths is that it gets rid of the need for classes filled with static methods. It is more appropriate to utilize global, extension and/or local functions instead, depending on your use case. Where I work we often define global extension functions in a separate, flat file with the naming convention: [className]Extensions.kt i.e., FooExtensions.kt. But more typically we write functions where they are needed inside their operating class or object.

对于Android使用从单个活动到所有必要活动的字符串。 就像java中的静态

public final static String TEA_NAME = "TEA_NAME";

Kotlin中的等效方法:

class MainActivity : AppCompatActivity() {
    companion object {
        const val TEA_NAME = "TEA_NAME"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

另一个需要价值的活动是:

val teaName = MainActivity.TEA_NAME