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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With