Kotlin 中 Java 静态方法的等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40352684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:37:36  来源:igfitidea点击:

What is the equivalent of Java static methods in Kotlin?

javakotlin

提问by pdeva

There is no statickeyword in Kotlin.

staticKotlin 中没有关键字。

What is the best way to represent a staticJava method in Kotlin?

static在 Kotlin 中表示Java 方法的最佳方式是什么?

采纳答案by Michael Anderson

You place the function in the "companion object".

您将函数放置在“伴随对象”中。

So the java code like this:

所以java代码是这样的:

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

will become

会变成

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

You can then use it from inside Kotlin code as

然后您可以在 Kotlin 代码中使用它作为

Foo.a();

But from within Java code, you would need to call it as

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

Foo.Companion.a();

(Which also works from within Kotlin.)

(这也适用于 Kotlin 内部。)

If you don't like having to specify the Companionbit you can either add a @JvmStaticannotation or name your companion class.

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

From the docs:

文档

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 @JvmStaticannotation. See the Java interoperability section for more details.

伴随对象

类中的对象声明可以用伴随关键字标记:

class MyClass {
   companion object Factory {
       fun create(): MyClass = MyClass()
   }
}

可以通过简单地使用类名作为限定符来调用伴生对象的成员:

val instance = MyClass.create()

...

但是,在 JVM 上,如果使用@JvmStatic注释,您可以将伴随对象的成员生成为真正的静态方法和字段。有关更多详细信息,请参阅 Java 互操作性部分。

Adding the @JvmStaticannotation looks like this

添加@JvmStatic注释看起来像这样

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

and then it will exist as a real Java static function, accessible from both Java and Kotlin as Foo.a().

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

If it is just disliked for the Companionname, then you can also provide an explicit name for the companion object looks like this:

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

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

which will let you call it from Kotlin in the same way, but from java like Foo.Blah.a()(which will also work in Kotlin).

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

回答by erluxman

A. Old Java Way :

A. 旧的 Java 方式:

  1. Declare a companion objectto enclose a static method / variable

    class Foo{
    companion object {
        fun foo() = println("Foo")
        val bar ="bar"  
        }
    }
    
  2. Use :

    Foo.foo()        // Outputs Foo    
    println(Foo.bar) // Outputs bar
    
  1. 声明 acompanion object以包含静态方法/变量

    class Foo{
    companion object {
        fun foo() = println("Foo")
        val bar ="bar"  
        }
    }
    
  2. 用 :

    Foo.foo()        // Outputs Foo    
    println(Foo.bar) // Outputs bar
    




B. New Kotlin way

B. 新的 Kotlin 方式

  1. Declare directly on file without classon a .ktfile.

    fun foo() = println("Foo")
    val bar ="bar"
    
  2. Use the methods/variableswith their names. (After importing them)

    Use :

    foo()        // Outputs Foo          
    println(bar) // Outputs bar     
    
  1. 直接在文件上声明而不在文件上声明.kt

    fun foo() = println("Foo")
    val bar ="bar"
    
  2. methods/variables与他们的名字一起使用。(导入后

    用 :

    foo()        // Outputs Foo          
    println(bar) // Outputs bar     
    


回答by Henrik F.

Docsrecommends to solve most of the needs for static functions with package-level functions. They are simply declared outside a class in a source code file. The package of a file can be specified at the beginning of a file with the package keyword.

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

Declaration

宣言

package foo

fun bar() = {}

Usage

用法

import foo.bar

Alternatively

或者

import foo.*

You can now call the function with:

您现在可以使用以下命令调用该函数:

bar()

or if you do not use the import keyword:

或者如果您不使用 import 关键字:

foo.bar()

If you do not specify the package the function will be accessible from the root.

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

If you only have experience with java, this might seem a little strange. The reason is that kotlin is not a strictly object-oriented language. You could say it supports methods outside of classes.

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

Edit: They have edited the documentation to no longer include the sentence about recommending package level functions. Thisis the original that was referred to above.

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

回答by ice1000

Write them directly to files.

将它们直接写入文件。

In Java (ugly):

在 Java 中(丑陋):

package xxx;
class XxxUtils {
  public static final Yyy xxx(Xxx xxx) { return xxx.xxx(); }
}

In Kotlin:

在科特林:

@file:JvmName("XxxUtils")
package xxx
fun xxx(xxx: Xxx): Yyy = xxx.xxx()

Those two pieces of codes are equaled after compilation (even the compiled file name, the file:JvmNameis used to control the compiled file name, which should be put just before the package name declaration).

这两段代码编译后相等(即使是编译后的文件名,file:JvmName用于控制编译后的文件名,应该放在包名声明之前)。

回答by Rajesh Dalsaniya

You need to pass companion object for static method because kotlin don't have static keyword - Members of the companion object can be called by using simply the class name as the qualifier:

您需要为静态方法传递伴随对象,因为 kotlin 没有 static 关键字 - 可以通过简单地使用类名作为限定符来调用伴随对象的成员:

package xxx
    class ClassName {
              companion object {
                       fun helloWord(str: String): String {
                            return stringValue
                      }
              }
    }

回答by Asharali V U

Use objectto represent val/var/method to make static. You can use object instead of singleton class also. You can use companionif you wanted to make static inside of a class

使用object表示 val/var/method 使其成为静态。您也可以使用 object 而不是单例类。如果您想在类中静态化,可以使用伴侣

object Abc{
     fun sum(a: Int, b: Int): Int = a + b
    }

If you need to call it from Java:

如果您需要从 Java 调用它:

int z = Abc.INSTANCE.sum(x,y);

In Kotlin, ignore INSTANCE.

在 Kotlin 中,忽略 INSTANCE。

回答by yasincidem

Simply you need to create a companion object and put the function in it

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

  class UtilClass {
        companion object {
  //        @JvmStatic
            fun repeatIt5Times(str: String): String = str.repeat(5)
        }
    }


To invoke the method from a kotlin class:

要从 kotlin 类调用该方法:

class KotlinClass{
  fun main(args : Array<String>) { 
    UtilClass.repeatIt5Times("Hello")
  }
}

or Using import

或使用导入

import Packagename.UtilClass.Companion.repeatIt5Times
class KotlinClass{
  fun main(args : Array<String>) { 
     repeatIt5Times("Hello")
  }
}


To invoke the method from a java class:

要从 Java 类调用该方法:

 class JavaClass{
    public static void main(String [] args){
       UtilClass.Companion.repeatIt5Times("Hello");
    }
 }

or by adding @JvmStatic annotation to the method

或者通过在方法中添加 @JvmStatic 注释

class JavaClass{
   public static void main(String [] args){
     UtilClass.repeatIt5Times("Hello")
   }
}

or both by adding @JvmStatic annotation to the method and making static import in java

或两者都通过在方法中添加 @JvmStatic 注释并在 java 中进行静态导入

import static Packagename.UtilClass.repeatIt5Times
class JavaClass{
   public static void main(String [] args){
     repeatIt5Times("Hello")
   }
}

回答by Shohel Rana

Kotlin has no any static keyword. You used that for java

Kotlin 没有任何静态关键字。你把它用于java

 class AppHelper {
        public static int getAge() {
            return 30;
        }
    }

and For Kotlin

对于 Kotlin

class AppHelper {
        companion object {
            fun getAge() : Int = 30
        }
    }

Call for Java

调用 Java

AppHelper.getAge();

Call for Kotlin

呼吁 Kotlin

AppHelper.Companion.getAge();

I think its working perfectly.

我认为它的工作完美。

回答by Shihab Uddin

Let, you have a class Student. And you have one staticmethod getUniversityName()& one staticfield called totalStudent.

让,你有一个类Student。您有一个静态方法getUniversityName()和一个名为totalStudent 的静态字段。

You should declare companion objectblock inside your class.

你应该在你的类中声明伴随对象块。

companion object {
 // define static method & field here.
}

Then your class looks like

然后你的班级看起来像

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

Then you can use those static method and fields like this way.

然后你可以像这样使用那些静态方法和字段。

println("University : " + Student.getUniversityName() + ", Total Student: " + Student.totalStudent)
    // Output:
    // University : MBSTU, Total Student: 30

回答by Waqar UlHaq

You can achieve the static functionality in Kotlin by Companion Objects

您可以通过Companion Objects实现 Kotlin 中的静态功能

  • Adding companionto the object declaration allows for adding the staticfunctionality to an object even though the actual static concept does not exist in Kotlin.
  • A companion objectcan access all members of the class too, including the private constructors.
  • A companion objectis initialized when the class is instantiated.
  • A companion objectcannot 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"
            }
    
        }
    }
    
  • 即使 Kotlin 中不存在实际的静态概念,也可以向对象声明添加伴侣,从而可以向对象添加 静态功能。
  • 一个同伴对象可以访问类的所有成员也包括私有的构造。
  • 一个同伴对象时,类实例被初始化。
  • 一个同伴对象不能在类之外声明。

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

Members of the companion object can be called by using simply the class name as the qualifier:

可以通过简单地使用类名作为限定符来调用伴生对象的成员:

Output:

输出:

MyClass.staticField // This is an example of static field Object Decleration

MyClass.getStaticFunction() : // This is an example of static function for Object Decleration