Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Kotlin class be extended to conform to an Interface (like Swift classes can)?

Tags:

swift

kotlin

In Swift, I can create a protocol that does something like

protocol FoobarConvertible {
    var foobar:String { get }
}

And then extend any class in the system with a conforming implementation

extension String : FoobarConvertible {
    var foobar:String {
        get {
            return "foobar"
        }
    }
}

In Kotlin, I think Interfaces are similar to protocols(?), and I can declare one like this

protocol FoobarConvertible {
    val foobar:String
}

But what's not apparent to me from the documentation (which seem to be an exercise in brevity), is how I would extend Kotlin's String class so that it conformed to FoobarConvertible. Obviously, I could just add an extension method to a Kotlin String

val String.foobar:String
    get() = "foobar"

But this does not allow Strings to then be used as parameters where a FoobarConvertible is the expected type.

like image 644
Travis Griggs Avatar asked Jul 05 '18 17:07

Travis Griggs


1 Answers

Kotlin doesn't have this language feature, extension functions and extension properties are as far as the extension features go - these are available because they can be implemented via static helper methods that just get the receiver of the extension as their first parameter.

However, interfaces can not be added to existing classes that you might not be compiling yourself - that feature would be more than syntactic sugar. (On the JVM, at least.)

like image 127
zsmb13 Avatar answered Sep 27 '22 17:09

zsmb13