Declaring a static interface field in Kotlin

Viewed 3807

Is it possible to write the equivalent of Java

interface Foo {
    public static final INSTANCE = new Foo {};
}

in Kotlin?

If Foo were a class, I could use:

class Foo {
    companion object {
        @JvmField
        val INSTANCE = object : Foo() {}
    }
}

but with an interface it gives an error:

JvmField cannot be applied to a property defined in companion object of interface

@JvmStatic doesn't work either.

2 Answers

From Kotlin 1.3 on you can do:

interface Foo {
    companion object {
        @JvmField val INSTANCE = object : Foo {}
    }
}

And call it from Java as Foo.INSTANCE.

The following works for me.

interface Foo {

    fun bar()

    companion object {
        val INSTANCE = object : Foo { // There are no () An interface cannot be instantiated.
            override fun bar() {
                //Do something
                ...
            }
        }
    }
}

Then in your activity, simply calling Foo.INSTANCE returns an instance to Foo.

Related