Travis Griggs
Travis Griggs

Reputation: 22252

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

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

interface 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.

Upvotes: 13

Views: 2982

Answers (1)

zsmb13
zsmb13

Reputation: 89578

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.)

Upvotes: 9

Related Questions