Hi Team :wave: Quick Question - Interface in Kotl...
# multiplatform
d
Hi Team 👋 Quick Question - Interface in Kotlin is reference type whereas Protocols in Swift don't have an inherent type classification. How to leverage the protocol like construct using the KMP? For example:
Copy code
struct HeadlessPaymentOptionsResponse: Codable, Equatable {
    let param2: String
    let param1: String
}
cc @chandilsachin
w
I don't exactly understand what reference types have to do with this, it's possible for a language with only references to implement what Swift's protocols bring. Kotlin's closest construct is an interface. This too is something that only describes behavior (and no implementation). But unlike Swift, you cannot have static members, you can only add conformance to an interface implementation at the declaration (not as an extension), we have no notion of
Self
, and there is there are no constructs such as implicit conformance or automatically generated members. Because of lack of static interface members, in Kotlin we don't have
Codable
. And because of JVM, sadly every type is kind of
Equatable
(every class inherits
Any
, which has
fun equals(other: Any?)
). If you would try to make your own
Equatable
, that would be impossible because of lack of
Self
type (there's a hack to kind of get this self type, but it's not even worth mentioning) So I can't really show your example, but I'll show an example with
Sequence
from Swift instead.
Copy code
interface Sequence<Element> { // Closest equivalent to Swift's `Sequence` protocol.
    fun makeIterator(): Iterator<Element>
}

class MySingletonSequence<T>(private val item: T) : Sequence<T> {
    fun makeIterator(): Iterator<T> = ...
}
c
@Wout Werkman Thanks for your detailed response 🙏. IMO @Dhruv Singh wants to mention that Like
struct
(Value Type) can conform to a
Codable
protocol. Does KMM allows us to create similar construct (like Interface, a closest construct) which Struct can conform? AFAIK, KMM would expose an
interface
(Reference type), which a
struct
(Value type) can't
conform/implement
. Pls Correct me if I am wrong.
w
Ah I see. Yes you are right. Neither the default Objective-C export, SKIE by Touchlab, nor Swift export support this. And indeed, since Kotlin does not have witness tables like Swift, if this were to be support, it would probably box the struct. (Even once Kotlin will support value types, I see personally see no other solution than it being boxed on every downcast, even on the JVM).