Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access Kotlin’s `hashCode` and `equals` methods from shared’s code interface in Swift?

In KMM application in shared module I have interface, let’s say it’s marker interface without any actual fields

interface Marker

In Kotlin I can use equals and hashCode on instances of that interface

fun isEqual(o1: Marker, o2: Marker): Boolean {
    return o1 == o2
}

How I can do same thing in iosApp Swift code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

func isEqual(o1: shared.Marker, o2: shared.Marker): Bool {
    // todo implement
}

I tried to invoke equals and hashCode methods on instances on Swift, but I got the error, that this methods don’t exist

>Solution :

Kotlin Native convert interfaces to Swift protocols. But methods equals, hashCode and toString are provided by kotlin.Any abstract class. These methods converts to NSObject’s method isEquals(_:) and the properties hash, description in Swift. Take a look at documentation for more details.

So basically you can implement what you want using cast to NSObject

func isEqual(o1: shared.Marker, o2: shared.Marker): Bool {
    return (o1 as! NSObject).isEquals(o2 as! NSObject)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading