在Kotlin中没有静态关键字。

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


当前回答

object objectName {
    fun funName() {

    }
}

其他回答

Docs建议使用包级函数来解决静态函数的大部分需求。它们只是在源代码文件中的类之外声明的。文件的包可以在文件的开头用关键字package指定。

宣言

package foo

fun bar() = {}

使用

import foo.bar

另外

import foo.*

你现在可以调用函数:

bar()

或者不使用import关键字:

foo.bar()

如果不指定包,则可以从根目录访问该函数。

如果您只有java经验,这可能看起来有点奇怪。原因是kotlin不是严格的面向对象语言。你可以说它支持类之外的方法。

编辑: 他们编辑了文档,不再包含关于推荐包级函数的句子。这是上面提到的原稿。

使用@JVMStatic Annotation

companion object {

    // TODO: Rename and change types and number of parameters
    @JvmStatic
    fun newInstance(param1: String, param2: String) =
            EditProfileFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
}

除了迈克尔安德森的回答,我在我的项目中有其他两种编码方式。

第一:

你可以把所有变量白到一个类。 创建一个名为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);

A.旧Java方式:

声明一个伴随对象来包含一个静态方法/变量 类Foo { 伴随对象{ fun foo() = println(" foo ") Val bar ="bar" } } 使用: Foo. Foo() //输出Foo println(Foo.bar) //输出bar



B.新的Kotlin方式

直接在文件上声明,而不需要在.kt文件上使用类。 fun foo() = println(" foo ") Val bar ="bar" 使用方法/变量的名称。(导入后) 使用: foo() //输出foo println(bar) //输出bar


你把函数放在“同伴对象”中。

java代码是这样的:

class Foo {
  public static int a() { return 1; }
}

将成为

class Foo {
  companion object {
     fun a() : Int = 1
  }
}

然后,您可以在Kotlin代码中作为

Foo.a();

但是在Java代码中,您需要将其调用为

Foo.Companion.a();

(也可以在Kotlin内部工作。)

如果您不喜欢指定Companion位,您可以添加@JvmStatic注释或命名您的Companion类。

从文档中可以看出:

Companion Objects An object declaration inside a class can be marked with the companion keyword: class MyClass { companion object Factory { fun create(): MyClass = MyClass() } } Members of the companion object can be called by using simply the class name as the qualifier: val instance = MyClass.create() ... However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the @JvmStatic annotation. See the Java interoperability section for more details.

添加@JvmStatic注释如下所示

class Foo {
  companion object {
    @JvmStatic
    fun a() : Int = 1;
  }
}

然后它将作为一个真正的Java静态函数存在,从 Java和Kotlin的Foo.a()。

如果只是不喜欢Companion名称,那么也可以 为同伴对象提供一个显式的名称,如下所示:

class Foo {
  companion object Blah {
    fun a() : Int = 1;
  }
}

这将让您以同样的方式从Kotlin调用它,但是 来自java,如Foo.Blah.a()(这也可以在Kotlin中工作)。