web-dev-qa-db-ja.com

KotlinのJava静的メソッドと同等のものは何ですか?

Kotlinにはstaticキーワードはありません。

Kotlinでstatic Javaメソッドを表現するための最良の方法は何ですか?

443
pdeva

関数を "コンパニオンオブジェクト"に配置します。

だから、このような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アノテーションを追加するか、コンパニオンクラスに名前を付けることができます。

docs :から

コンパニオンオブジェクト

クラス内のオブジェクト宣言は、companionキーワードでマークできます。

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

コンパニオンオブジェクトのメンバは、クラス名を修飾子として使用することで呼び出すことができます。

val instance = MyClass.create()

...

ただし、@JvmStaticアノテーションを使用すると、JVM上で、コンパニオンオブジェクトのメンバーを実際の静的メソッドおよびフィールドとして生成できます。詳細については、Javaの相互運用性の節を参照してください。

@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からも同じように呼び出すことができますが、Foo.Blah.a()のようなJavaからも呼び出すことができます(Kotlinでも機能します)。

640

ドキュメント は静的関数の必要性のほとんどをパッケージレベル関数で解決することを推奨します。それらは単にソースコードファイルのクラスの外側で宣言されています。ファイルのパッケージは、packageキーワードを使用してファイルの先頭に指定できます。

宣言

package foo

fun bar() = {}

使用法

import foo.bar

代替

import foo.*

これで関数を呼び出すことができます。

bar()

インポートキーワードを使用しない場合

foo.bar()

パッケージを指定しないと、関数はルートからアクセス可能になります。

Javaの経験しかないのであれば、これは少し奇妙に思えるかもしれません。その理由は、kotlinは厳密なオブジェクト指向言語ではないからです。あなたはそれがクラス外のメソッドをサポートしていると言えるでしょう。

98
Henrik F.

静的な メソッド/変数 を囲むにはcompanion objectを使用します

class Foo{
    companion object {
        fun sayFoo() = println("Foo")
        val bar ="bar"  
    }
}

2.使用法:

Foo.sayFoo()        // Output Foo    
println(Foo.bar) .  // Output Bar
19
erluxman

静的にするためのval/var/methodを表すには object を使用します。シングルトンクラスの代わりにオブジェクトを使うこともできます。クラス内で静的にしたい場合は companion を使用できます。

object Abc{
     fun sum(a: Int, b: Int): Int = a + b
    }
17
Asharali V U

Kotlinにはstaticキーワードがないため、staticメソッドにはcompanionオブジェクトを渡す必要があります。修飾子としてクラス名を使用するだけで、companionオブジェクトのメンバーを呼び出すことができます。

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

これも私のために働いた

object Bell {
    @JvmStatic
    fun ring() { }
}

コトリン発の

Bell.ring()

javaから

Bell.ring()
4
Samuel

Kotlinで静的に適用できる方法は2つあります。

最初にクラスの下にコンパニオンオブジェクトを作ります

例:

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

ハッピーコーディング!

4
Android Geek
object objectName {
    fun funName() {

    }
}
4
Umesh Maharjan

Kotlinには静的キーワードはありません。あなたはJavaのためにそれを使用しました

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

とコトリンの

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

Javaを呼ぶ

AppHelper.getAge();

コトリンの呼びかけ

AppHelper.Companion.getAge();

私はそれが完璧に機能していると思います。

3
Shohel Rana

上記の回答に何か追加したいと思います。

はい、あなたはソースコードファイル(クラス外)で関数を定義することができます。ただし、 Companion Object を使用してクラス内で静的関数を定義すると、 Kotlin Extensions を利用して静的関数を追加できるため、より便利です。

class MyClass {
    companion object { 
        //define static functions here
    } 
}

//Adding new static function
fun MyClass.Companion.newStaticFunction() {
    // ...
}

また、Companion Object内の関数を呼び出すのと同じように、上で定義した関数を呼び出すことができます。

3
SVB-knowmywork

単にあなたはコンパニオンオブジェクトを作成し、その中に関数を入れる必要があります。

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

コンパニオンオブジェクトは、Javaのstaticキーワードの代替であり、クラスまたはメソッドをコンパニオンオブジェクトとして宣言することで静的にすることができます。
同じクラス内から呼び出している場合でも、コンパニオンオブジェクトをクラス名で修飾する必要はありません。

例えば:

class SomeClass() {

    val id: Int

    init {
       id = nextId++       
    }

    private companion object {
       var nextId = 1
    }
}

fun main(args: Array<String>) {
    repeat(2) { 
        println(SomeClass().id)
    }
} 
2
Shubham Mittal

コンパニオンオブジェクト以外のオブジェクトも使用できます

object Utils {
    fun someFunction()
}

したがって、これはメソッドが呼び出されたときのようになります。

Utils.someFunction()
2
dr3k

短くするには、 "companion object" を使用してKotlin静的世界に入ることができます。

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

また、定数フィールドを作成するには、コードのように "const val" を使用します。

2
amir naghavi

コンパニオンオブジェクトを作成し、そのメソッドにjvmstaticアノテーションを付ける

2
user9092442

Javaの静的メソッドから等価のkotlinへの正確な変換は次のようになります。例えばここでutilクラスには、Javaとkotlinの両方で同等の静的メソッドが1つあります。 @JvmStatic の使用は重要です。

 //Java
class Util{
     public static String capitalize(String text){
     return text.toUpperCase();}
   }



//Kotlin
class Util {
    companion object {
        @JvmStatic
        fun capitalize(text:String): String {
            return text.toUpperCase()
        }
    }
}
2
Lalit Behera

「コンパニオンオブジェクトまたは名前付きオブジェクト」内の関数を使用してください。

コンパニオンオブジェクトの例を参照してください。

   class Foo {
  companion object {
     fun square(x : Int) : Int = x*x
  }
}

名前付きオブジェクトの例を参照

object Foo{
   fun square(x : Int) : Int = x*x
}

でアクセスできます

val k = Foo.square(12)
2
Sabin ks

これは2年以上前のもので、たくさんの素晴らしい答えがありましたが、「静的な」Kotlinフィールドを取得するための他の方法がいくつか欠けているのがわかります。これがKotlin-Java static interopのためのガイド例です:

シナリオ1:Kotlin for Javaで静的メソッドを作成する

コトリン

@file:JvmName("KotlinClass") //This provides a name for this file, so it's not defaulted as [KotlinClassKt] in Java
package com.frybits

class KotlinClass {
    companion object {

        //This annotation tells Java classes to treat this method as if it was a static to [KotlinClass]
        @JvmStatic
        fun foo(): Int = 1

        //Without it, you would have to use [KotlinClass.Companion.bar()] to use this method.
        fun bar(): Int = 2
    }
}

Java

package com.frybits;

class JavaClass {

    void someFunction() {
        println(KotlinClass.foo()); //Prints "1"
        println(KotlinClass.Companion.bar()); //Prints "2". This is the only way to use [bar()] in Java.
        println(KotlinClass.Companion.foo()); //To show that [Companion] is still the holder of the function [foo()]
    }

    //Because I'm way to lazy to keep typing [System.out], but I still want this to be compilable.
    void println(Object o) {
        System.out.println(o);
    }
}

Michael Andersonの答えはこれ以上の深さを提供するので、このシナリオでは間違いなく参照されるべきです。


この次のシナリオでは、Kotlinで静的フィールドを作成して、静的関数が不要な場合にJavaがKotlinClass.foo()を呼び出し続ける必要がないようにします。

シナリオ2:Kotlin for Javaで静的変数を作成する

コトリン

@file:JvmName("KotlinClass") //This provides a name for this file, so it's not defaulted as [KotlinClassKt] in Java
package com.frybits

class KotlinClass {

    companion object {

        //This annotation tells Kotlin to not generate the getter/setter functions in Java. Instead, this variable should be accessed directly
        //Also, this is similar to [@JvmStatic], in which it tells Java to treat this as a static variable to [KotlinClass].
        @JvmField
        var foo: Int = 1

        //If you want something akin to [final static], and the value is a primitive or a String, you can use the keyword [const] instead
        //No annotation is needed to make this a field of [KotlinClass]. If the declaration is a non-primitive/non-String, use @JvmField instead
        const val dog: Int = 1

        //This will be treated as a member of the [Companion] object only. It generates the getter/setters for it.
        var bar: Int = 2

        //We can still use [@JvmStatic] for 'var' variables, but it generates getter/setters as functions of KotlinClass
        //If we use 'val' instead, it only generates a getter function
        @JvmStatic
        var cat: Int = 9
    }
}

Java

package com.frybits;

class JavaClass {

    void someFunction() {
        //Example using @JvmField
        println(KotlinClass.foo); //Prints "1"
        KotlinClass.foo = 3;

        //Example using 'const val'
        println(KotlinClass.dog); //Prints "1". Notice the lack of a getter function

        //Example of not using either @JvmField, @JvmStatic, or 'const val'
        println(KotlinClass.Companion.getBar()); //Prints "2"
        KotlinClass.Companion.setBar(3); //The setter for [bar]

        //Example of using @JvmStatic instead of @JvmField
        println(KotlinClass.getCat());
        KotlinClass.setCat(0);
    }

    void println(Object o) {
        System.out.println(o);
    }
}

Kotlinの優れた機能の1つは、トップレベルの関数と変数を作成できるということです。これは定数フィールドと関数の "クラスのない"リストを作成することを貪欲にします。そしてそれらはJavaのstatic関数/フィールドとして使用することができます。

シナリオ3:JavaからKotlinのトップレベルのフィールドと関数にアクセスする

コトリン

//In this example, the file name is "KSample.kt". If this annotation wasn't provided, all functions and fields would have to accessed
//using the name [KSampleKt.foo()] to utilize them in Java. Make life easier for yourself, and name this something more simple
@file:JvmName("KotlinUtils")

package com.frybits

//This can be called from Java as [KotlinUtils.TAG]. This is a final static variable
const val TAG = "You're it!"

//Since this is a top level variable and not part of a companion object, there's no need to annotate this as "static" to access in Java.
//However, this can only be utilized using getter/setter functions
var foo = 1

//This lets us use direct access now
@JvmField
var bar = 2

//Since this is calculated at runtime, it can't be a constant, but it is still a final static variable. Can't use "const" here.
val GENERATED_VAL:Long = "123".toLong()

//Again, no need for @JvmStatic, since this is not part of a companion object
fun doSomethingAwesome() {
    println("Everything is awesome!")
}

Java

package com.frybits;

class JavaClass {

    void someFunction() {

        println(KotlinUtils.TAG); //Example of printing [TAG]


        //Example of not using @JvmField.
        println(KotlinUtils.getFoo()); //Prints "1"
        KotlinUtils.setFoo(3);

        //Example using @JvmField
        println(KotlinUtils.bar); //Prints "2". Notice the lack of a getter function
        KotlinUtils.bar = 3;

        //Since this is a top level variable, no need for annotations to use this
        //But it looks awkward without the @JvmField
        println(KotlinUtils.getGENERATED_VAL());

        //This is how accessing a top level function looks like
        KotlinUtils.doSomethingAwesome();
    }

    void println(Object o) {
        System.out.println(o);
    }
}

Javaで「静的」フィールドとして使用できるもう1つの注目すべき言及は、Kotlinのobjectクラスです。これらは、最初の使用時に遅延インスタンス化されるゼロパラメータシングルトンクラスです。それらに関するより詳しい情報はここで見つけることができます: https://kotlinlang.org/docs/reference/object-declarations.html#object-declarations

しかし、シングルトンにアクセスするために、特別なINSTANCEオブジェクトが作成されます。これは、Companionと同様に扱うのが面倒です。アノテーションを使用して、Javaできれいなstaticを作成する方法は次のとおりです。

シナリオ4:objectクラスを使う

コトリン

@file:JvmName("KotlinClass")

//This provides a name for this file, so it's not defaulted as [KotlinClassKt] in Java
package com.frybits

object KotlinClass { //No need for the 'class' keyword here.

    //Direct access to this variable
    const val foo: Int = 1

    //Tells Java this can be accessed directly from [KotlinClass]
    @JvmStatic
    var cat: Int = 9

    //Just a function that returns the class name
    @JvmStatic
    fun getCustomClassName(): String = this::class.Java.simpleName + "boo!"

    //Getter/Setter access to this variable, but isn't accessible directly from [KotlinClass]
    var bar: Int = 2

    fun someOtherFunction() = "What is 'INSTANCE'?"
}

Java

package com.frybits;

class JavaClass {

    void someFunction() {
        println(KotlinClass.foo); //Direct read of [foo] in [KotlinClass] singleton

        println(KotlinClass.getCat()); //Getter of [cat]
        KotlinClass.setCat(0); //Setter of [cat]

        println(KotlinClass.getCustomClassName()); //Example of using a function of this 'object' class

        println(KotlinClass.INSTANCE.getBar()); //This is what the singleton would look like without using annotations
        KotlinClass.INSTANCE.setBar(23);

        println(KotlinClass.INSTANCE.someOtherFunction()); //Accessing a function in the object class without using annotations
    }

    void println(Object o) {
        System.out.println(o);
    }
}
1
Pablo Baxter

ファイルに直接書き込みます。

Javaでは(醜い):

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

コトリンでは:

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

これら2つのコードはコンパイル後に同等になります(コンパイルされたファイル名でもfile:JvmNameは、コンパイルされたファイル名を制御するために使用されます。これはパッケージ名宣言の直前に置かれるべきです)。

1
ice1000

さて、あなたはクラス Student を持っています。そして、 static method getUniversityName() &one static というフィールドが totalStudent にあります。

クラス内で companion object blockを宣言する必要があります。

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
1
Shihab Uddin

Javaの場合

public class Constants {
public static final long MAX_CLICK_INTERVAL = 1000;}

同等のKotlinコード:

object  Constants {
const val MAX_CLICK_INTERVAL: Long = 1000}

そのため、Javaの静的メソッドと同等のものは、Kotlinのオブジェクトクラスです。

1
Paulami Biswas

@JVMStaticアノテーションを使う

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)
                }
            }
}
1
ZafarHussain

すべての静的メンバと関数はコンパニオンブロックの中にあるべきです

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

    fun staticMethod() {
    }
  }
0
Rahul

Javaでは、次のように書くことができます

class MyClass {
  public static int myMethod() { 
  return 1;
  }
}

Kotlinでは、次のように書くことができます

class MyClass {
  companion object {
     fun myMethod() : Int = 1
  }
}

コンパニオンはKotlinで静的として使用されます。

0

多くの人がコンパニオンオブジェクトに言及していますが、これは正しいことです。しかし、ご存じのとおり、(classではなくobjectキーワードを使用して)あらゆる種類のオブジェクトを使用することもできます。

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

Javaの静的メソッドと同じように使用します。

StringUtils.toUpper("foobar")

そのようなパターンはKotlinでは無用のようなものですが、その長所の1つは、静的メソッドで満たされたクラスが不要になることです。ユースケースに応じて、代わりにグローバル、エクステンションおよび/またはローカル関数を利用することがより適切です。私が仕事をしているところでは、私たちはグローバルな拡張関数を別のフラットなファイルで命名規則を使って定義することがよくあります:しかし、より典型的には、それらがそれらのオペレーティングクラスまたはオブジェクトの中で必要とされるところに関数を書きます。

0
pranalli

Kotlinの静的機能は、 Companion Objects によって実現できます。

  • 実際の静的な概念がKotlinに存在しなくても、 companion をオブジェクト宣言に追加すると、 static 機能をオブジェクトに追加することができます。
  • コンパニオンオブジェクト は、プライベートコンストラクタを含め、クラスのすべてのメンバにもアクセスできます。
  • コンパニオンオブジェクト は、クラスがインスタンス化されたときに初期化されます。
  • コンパニオンオブジェクト は、クラスの外側で宣言することはできません。

    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
0
Waqar UlHaq

Kotlinドキュメントプロバイダーは、それを行う3つの方法を提供します。最初の方法は、クラスなしでパッケージに関数を定義することです。

package com.example

fun f() = 1

2番目は@JvmStaticアノテーションを使用します。

package com.example

class A{
@JvmStatic
fun f() = 1
}

3番目はコンパニオンオブジェクトの使用です。

package com.example

clss A{
companion object{
fun f() = 1
}
}
0
Du Jianyu

Javaコードは以下のようになります。

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

kotlinでは以下のようになります。

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

ただし、JVMで@JvmStaticアノテーションを使用すると、実際の静的メソッドおよびフィールドとして生成されたコンパニオンオブジェクトのメンバーを持つことができます。

0
hetsgandhi