简体   繁体   English

在 Java 中调用 Kotlin 函数

[英]Call Kotlin function in Java

I am a neophite in Kotlin.我是 Kotlin 的新手。 I need to call a method in a class created in Kotlin from a Java class.我需要从 Java 类调用在 Kotlin 中创建的类中的方法。 The class in question concerns the creation of the db.有问题的类涉及数据库的创建。

@Database(entities = arrayOf(Indirizzo::class, Dispositivo::class), version = 1, exportSchema = false)
abstract class WppDb : RoomDatabase() {
    abstract fun DispositivoDao(): DispositivoDao
    abstract fun IndirizzoDao(): IndirizzoDao

    private var INSTANCE : WppDb? = null

    fun getInstance(context: Context): WppDb? {
        if (INSTANCE == null) {
            synchronized(WppDb::class) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            WppDb::class.java, "weather.db")
                           .build()
            }
        }
        return INSTANCE
    }

    fun destroyInstance() {
        INSTANCE = null
    }
}

I need to call the getInstance() method from a Java Activity.我需要从 Java Activity 调用getInstance()方法。

If you want the equivalent of what Room samples usually show with a static Java field and static getter method for it, you can place those functions in the companion object of your class:如果您想要与 Room 示例通常显示的带有静态 Java 字段和静态 getter 方法的等效内容,您可以将这些函数放在类的伴随对象中:

@Database(entities = arrayOf(Indirizzo::class, Dispositivo::class), version = 1, exportSchema = false)
abstract class WppDb : RoomDatabase() {
    abstract fun DispositivoDao(): DispositivoDao
    abstract fun IndirizzoDao() : IndirizzoDao

    companion object {
        private var INSTANCE : WppDb? =  null

        @JvmStatic
        fun getInstance(context: Context): WppDb? {
            if (INSTANCE == null) {
                synchronized(WppDb::class) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                                    WppDb::class.java, "weather.db")
                                   .build()
                }
            }
            return INSTANCE
        }

        @JvmStatic
        fun destroyInstance() {
            INSTANCE = null
        }
    }
}

You can then call WppDb.getInstance(context) from either Kotlin or Java code.然后,您可以从 Kotlin 或 Java 代码调用WppDb.getInstance(context) Note the @JvmStatic annotations which make these calls nicer in Java - without them, you'd have to use WppDb.Companion to get the companion object, and then call the getInstance function on that (so WppDb.Companion.getInstance(context) altogether).请注意@JvmStatic注释,它使这些调用在 Java 中更好 - 没有它们,您必须使用WppDb.Companion来获取伴随对象,然后在其上调用getInstance函数(因此WppDb.Companion.getInstance(context)完全)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM