簡體   English   中英

Kotlin 中 Java 靜態方法的等價物是什么?

[英]What is the equivalent of Java static methods in Kotlin?

Kotlin 中沒有static關鍵字。

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

您將函數放置在“伴隨對象”中。

所以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關鍵字標記:

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

可以通過簡單地使用類名作為限定符來調用伴生對象的成員:

 val instance = MyClass.create()

...

但是,在 JVM 上,如果您使用@JvmStatic注釋,您可以將伴隨對象的成員生成為真正的靜態方法和字段。 有關更多詳細信息,請參閱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 中工作)。

Docs建議使用包級函數來解決大部分靜態函數的需求。 它們只是在源代碼文件中的類之外聲明。 文件的包可以在文件的開頭用 package 關鍵字指定。

聲明

package foo

fun bar() = {}

用法

import foo.bar

或者

import foo.*

您現在可以使用以下命令調用該函數:

bar()

或者如果您不使用 import 關鍵字:

foo.bar()

如果您不指定包,則可以從根訪問該函數。

如果您只有 Java 經驗,這可能看起來有點奇怪。 原因是 kotlin 不是嚴格的面向對象語言。 你可以說它支持類之外的方法。

編輯:他們編輯了文檔,不再包含關於推薦包級功能的句子。 是上面提到的原文。

A. 舊的 Java 方式:

  1. 聲明一個companion object來包含一個靜態方法/變量

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

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


B. 新的 Kotlin 方式

  1. 直接在文件上聲明.kt文件上沒有類

     fun foo() = println("Foo") val bar ="bar"
  2. 使用methods/variables及其名稱 導入后

    使用:

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

使用object表示 val/var/method 使其成為靜態。 您也可以使用 object 而不是單例類。 如果您想在類中靜態化,可以使用伴侶

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

如果您需要從 Java 調用它:

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

在 Kotlin 中,忽略 INSTANCE。

這也對我有用

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

來自科特林

Bell.ring()

來自爪哇

Bell.ring()
object objectName {
    fun funName() {

    }
}

盡管這已經有 2 年多的歷史了,並且有很多很好的答案,但我發現缺少其他一些獲取“靜態”Kotlin 字段的方法。 以下是 Kotlin-Java static互操作的示例指南:

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

爪哇

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

邁克爾安德森的回答提供了比這更深入的內容,並且絕對應該在這種情況下被引用。


下一個場景處理在 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 } }

爪哇

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 的一大特色是您可以創建頂級函數和變量。 這使得創建常量字段和函數的“無類”列表非常有用,這些列表又可以用作 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!") }

爪哇

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 中用作“靜態”字段的值得注意的是 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'?" }

爪哇

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

您需要為靜態方法傳遞伴隨對象,因為 kotlin 沒有 static 關鍵字 - 可以通過簡單地使用類名作為限定符來調用伴隨對象的成員:

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

有兩種方法可以在 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
       }
}

快樂編碼!

static屬性的頂級/ companion object

頂級

當屬性與類有些相關時,在類聲明之前將它們定義為頂級屬性:

const val MAX_ATTEMPTS = 3
private const val DEFAULT_NAME = "Guest"
private const val MIN_AGE = 16

data class User(val id: String, val name: String = DEFAULT_NAME)

這類似於 Java 中的static屬性。

當屬性完全獨立於任何類時,您可以在不包含類的單獨文件中將它們定義為頂級。

companion object

當屬性與類密切相關並且僅在該類中使用時,請在companion object定義它們:

data class User(val id: String, val name: String = DEFAULT_NAME) {
    companion object {
        const val DEFAULT_NAME = "Guest"
        const val MIN_AGE = 16
    }
}

static方法的頂級/ companion object

頂級

與上面的屬性類似,當函數與類有些相關時,將它們定義在類的正上方:

fun getAllUsers() { }

fun getProfileFor(userId: String) { }

data class User(val id: String, val name: String)

用法:

val userList = getAllUsers()

companion object

當函數與類密切相關時,將它們定義在一個companion object

data class User(val id: String, val name: String) {

    companion object {

        fun getAll() { }

        fun profileFor(userId: String) { }
    }
}

用法:

val userProfile = User.profileFor("34")

這類似於 Java 中的static方法。

頂級函數通常更符合 Kotlin 的習慣。 companion object定義函數的一個更好的理由是當您使用interface擴展companion object時。 單例部分顯示了一個示例。


static類的嵌套類

當具有相關功能的類屬於一起時,可以通過嵌套將它們組合在一起:

class User(val id: String, val name: String) {
    class UserAccess : UserDao {
        override fun add(user: User) { }
        override fun remove(id: String) { }
    }
}

這相當於 Java 中的static嵌套類。 這里的UserAccess類實現了一個interface UserDao

用法:

fun main() {
    val john = User("34", "John")
    val userAccess = User.UserAccess()
    userAccess.add(john)
}

static INSTANCE單例object

頂級

當您只需要一個類的單個對象時,您不再需要像在 Java 中那樣在類中創建static INSTANCE 只需使用頂級object聲明:

object UserAccess : UserDao {
    override fun add(user: User) { }
    override fun remove(id: String) { }
}

還要注意在單例中擴展interfaceclass是多么容易。

上面的代碼,在底層,在 Java(簡化)中產生了以下static INSTANCE單例模式:

public final class UserAccess implements UserDao {
   public static final UserAccess INSTANCE;

   public void add(User user) { }

   public void remove(String id) { }

   private UserAccess() { }

   static { INSTANCE = new UserAccess();}
}

companion object

當單例與類密切相關時,使用companion object

data class User(val id: String, val name: String) {
    companion object : UserDao {
        override fun add(user: User) { }
        override fun remove(id: String) { }
    }
}

通過這種方式,您可以獲得更優雅的命名: User.add(john) 此外,您明確表示此單例僅用作User類的實用程序。 如果您想要多個單例或函數/屬性組,您也可以在類中使用沒有companion關鍵字的object


static工廠的companion object

Koltin 中的工廠函數是使用companion object創建的。 當您想要提供多種方法來創建對象時,工廠函數非常有用,但對象構造過程很復雜,或者當多個構造函數不夠表達時。

例如,以下代碼段中的newInstance()工廠函數通過自動生成id創建用戶:

class User private constructor(val id: Long, val name: String) {
    companion object {
        private var currentId = 0L;
        fun newInstance(name: String) = User(currentId++, name)
    }
}

這相當於 Java 中的static工廠方法。

constructorprivatecompanion object可以訪問constructor

在上面的代碼中,保證了下一代id一致性,因為companion object是單例,只有一個對象會跟蹤id ,不會有任何重復的 id。

另請注意,伴隨對象可以具有表示狀態的屬性(在本例中為currentId )。

用法:

val john = User.newInstance("John")

@JvmStatic實現 Java 互操作性

Kotlin 中不存在 Java 的靜態概念。 companion object是名為Companion的真實class的實例。 因此,當您從 Java 調用 Kotlin 代碼時,首先在幕后實例化Companion類的一個對象。 您需要使用 Java 中的Companion對象調用該函數:

Profile userProfile = User.Companion.profileFor("34");

對於慣用的 Java 命名和更少的冗長,在該函數或屬性上使用@JvmStatic注釋:

companion object {
    @JvmStatic
    fun profileFor(userId: String): Profile { }
}

@JvmStatic注釋創建了getProfileFor()函數的一個單獨的純static副本。 現在您可以通過常規語法從 Java 中使用它:

Profile userProfile = User.profileFor("34");

就是這樣! 希望這些示例對您的項目有用。

只需創建一個伴隨對象並將函數放入其中

  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 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 沒有任何靜態關鍵字。 您可以將以下代碼用於 Java 和 Kotlin

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

調用 Java 類

AppHelper.getAge();

呼吁 Kotlin 課程

AppHelper.getAge()

它非常適合我。 謝謝

伴隨對象是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)
    }
} 

我想在上面的答案中添加一些內容。

是的,您可以在源代碼文件(類外)中定義函數。 但是如果您使用Companion Object在類中定義靜態函數會更好,因為您可以通過利用Kotlin Extensions添加更多靜態函數。

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

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

您可以調用上面定義的函數,就像調用 Companion Object 中的任何函數一樣。

對於 Java:

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

等效的 Kotlin 代碼:

object  Constants {
const val MAX_CLICK_INTERVAL: Long = 1000}

因此,對於 Java 靜態方法的等價物是 Kotlin 中的對象類。

簡而言之,您可以使用“伴隨對象”進入 Kotlin 靜態世界,例如:

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

並在代碼中使用“const val”作為常量字段。 但是盡量避免使用靜態類,因為它在使用 Mockito! 進行單元測試時會遇到困難。

對於 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

java 靜態方法到 kotlin 等效方法的確切轉換是這樣的。 例如,這里的 util 類有一個靜態方法,它在 java 和 kotlin 中都是等價的。 @JvmStatic的使用很重要。

爪哇代碼:

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

科特林代碼:

    class Util {
        companion object {
            @JvmStatic
            fun capitalize(text:String): String {
                return text.toUpperCase()
            }
        }
    }

除了邁克爾安德森的回答,我在我的項目中用其他兩種方式編碼。

首先:

您可以將所有變量都設置為一個類。 創建了一個名為 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);

將它們直接寫入文件。

在 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()

這兩段代碼編譯后相等(即使是編譯后的文件名, file:JvmName用於控制編譯后的文件名,應該放在包名聲明之前)。

讓,你有一個類Student 您有一個靜態方法getUniversityName()和一個名為totalStudent 的靜態字段。

你應該在你的類中聲明伴隨對象塊。

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

您可以通過Companion Objects實現 Kotlin 中的靜態功能

  • 即使 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" } } }

可以通過簡單地使用類名作為限定符來調用伴生對象的成員:

輸出:

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

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

java代碼如下:

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

將在kotlin中變為如下:

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

但是,在JVM上使用@JvmStatic注釋,我們可以將伴隨對象的成員生成為真正的靜態方法和字段。

使用@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)
                }
            }
}

很多人提到伴隨對象,這是正確的。 但是,正如您所知,您也可以使用任何類型的對象(使用 object 關鍵字,而不是類),即,

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

像java中的任何靜態方法一樣使用它:

StringUtils.toUpper("foobar")

不過,這種模式在 Kotlin 中是無用的,它的優勢之一是它擺脫了對充滿靜態方法的類的需求。 根據您的用例,使用全局、擴展和/或本地函數更合適。 在我工作的地方,我們經常使用命名約定在一個單獨的平面文件中定義全局擴展函數:[className]Extensions.kt,即 FooExtensions.kt。 但更常見的是,我們在操作類或對象中需要的地方編寫函數。

kotlin 中沒有 static 關鍵字。 如果你想遵循 DRY,kotlin docs 建議使用包級函數。 創建一個擴展名為.kt的文件並將您的方法放入其中。

package p
    fun m(){
    //fun body
    }

編譯后m將有一個public static final void的簽名

import p.m

只需使用這種方法

object Foo{
   fun foo() = println("Foo")
   val bar ="bar"  
}

Foo.INSTANCE.foo()

在Java中,我們可以用下面的方式編寫

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

在 Kotlin 中,我們可以這樣寫

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

同伴在 Kotlin 中用作靜態。

kotlin 文檔提供者可以通過三種方式做到這一點,第一種是在包中定義函數,無需類:

package com.example

fun f() = 1

第二種是使用@JvmStatic 注解:

package com.example

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

第三個是使用伴隨對象:

package com.example

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

所有靜態成員和函數都應該在伴隨塊內

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

    fun staticMethod() {
    }
  }

如果您需要將一個函數或屬性綁定到一個類而不是它的實例,您可以在伴隨對象中聲明它:

class Car(val horsepowers: Int) {
    companion object Factory {
        val cars = mutableListOf<Car>()

        fun makeCar(horsepowers: Int): Car {
            val car = Car(horsepowers)
            cars.add(car)
            return car
        }
    }
}

伴生對象是一個單例,可以通過包含類的名稱直接訪問其成員

val car = Car.makeCar(150)
println(Car.Factory.cars.size)

您可以使用伴隨對象 - kotlinlang

它可以通過首先創建該接口來顯示

interface I<T> {

}

然后我們必須在該接口內創建一個函數:

fun SomeFunc(): T

然后,我們需要一個類:

class SomeClass {}

在該類中,我們需要該類中的一個伴生對象:

companion object : I<SomeClass> {}

在 Companion 對象中,我們需要舊的SomeFunc函數,但我們需要覆蓋它:

override fun SomeFunc(): SomeClass = SomeClass()

最后,在所有這些工作之后,我們需要一些東西來為靜態函數提供動力,我們需要一個變量:

var e:I<SomeClass> = SomeClass()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM