https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Rob Elliot

03/21/2024, 7:20 PM
I'm sure this is old news and a sign of how little I read, but... I've often found myself hankering for the ability to declare a type I don't own implements an interface the way you can in Haskell - I just had a revelation that of course you can:
Copy code
package module1

data class Thing1(val name: String)

package module2

interface Named {
  val name: String
}

fun Thing1.asNamed() = object : Named {
  override val name: String = <mailto:this@asNamed.name|this@asNamed.name>
}
Does this seem wise? First thing that strikes me is that the anonymous object's equals, hashCode and toString are not going to be nice...
j

Jeff Lockhart

03/21/2024, 7:41 PM
equals, hashCode and toString are not going to be nice
You could overcome this with a class like this one I use in my KMP library to wrap platform implementations. It also has an
actual
property to access the wrapped object directly.
r

Rob Elliot

03/21/2024, 7:42 PM
Good idea, that’s nice
j

Jeff Lockhart

03/21/2024, 7:51 PM
I also have one that wraps Objective-C `NSObject`s for Kotlin/Native as well. I'm using a similar concept, just with expect/actual classes rather than interfaces.
y

Youssef Shoaib [MOD]

03/21/2024, 8:23 PM
If you control the interface, you can actually do a typeclass-esque pattern with contexts:
Copy code
interface Summable<T> {
operator fun T.plus(other: T): T
}
object IntSummable: Summable<Int> { ... }
context(Summable<T>) fun List<T>.sum() = ...
// Usage
with(IntSummable) { myList.sum() }
2 Views