Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to specify a static function in a Kotlin interface?

I want to do something like this:

interface Serializable<FromType, ToType> {
    fun serialize(): ToType
    companion object {
        abstract fun deserialize(serialized: ToType): FromType
    }
}

or even this would work for me:

interface Serializable<ToType> {
    fun serialize(): ToType
    constructor(serialized: ToType)
}

but neither compiles. Is there a syntax for this, or will I be forced to use make this an interface for a factory? Or is there another answer? 😮 That'd be neat!

like image 517
Ky. Avatar asked Nov 02 '16 00:11

Ky.


People also ask

Can we define function in interface in Kotlin?

In Kotlin, the interface works exactly similar to Java 8, which means they can contain method implementation as well as abstract methods declaration. An interface can be implemented by a class in order to use its defined functionality.

Can we use static in Kotlin?

Android Dependency Injection using Dagger with Kotlin In Java, once a method is declared as "static", it can be used in different classes without creating an object. With static methods, we don't have to create the same boilerplate code for each and every class.

Why there is no static in Kotlin?

Kotlin is known primarily as a drop-in replacement for Java, but it gets rid of a well-known Java construct: the static keyword. Instead, that class-level functionality is offered mainly by companion objects.


1 Answers

Basically, nothing in a companion object can be abstract or open (and thus be overridden), and there's no way to require the implementations' companion objects to have a method or to define/require a constructor in an interface.

A possible solution for you is to separate these two functions into two interfaces:

interface Serializable<ToType> {
    fun serialize(): ToType
}

interface Deserializer<FromType, ToType> {
    fun deserialize(serialized: ToType): FromType
}

This way, you will be able to implement the first interface in a class and make its companion object implement the other one:

class C: Serializable<String> {
    override fun serialize(): String = "..."

    companion object : Deserializer<C, String> {
        override fun deserialize(serialized: String): C = C()
    }
}

Also, there's a severe limitation that only a single generic specialization of a type can be used as a supertype, so this model of serializing through the interface implementation may turn out not scalable enough, not allowing multiple implementations with different ToTypes.

like image 181
hotkey Avatar answered Oct 15 '22 23:10

hotkey