I'm sure this is old news and a sign of how little...
# getting-started
r
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
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
Good idea, that’s nice
j
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
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() }