As someone coming from Rust, i have grown deeply in love with the use of the Into/From traits. This has led me to want to implement something similar in Kotlin, but it has proved difficult to do so.
The main issue starts with the fact that apparently a class cannot inherent more than once from the same interface. This does not make very much sense to me, see this example:
interface Into<U> {
fun into(): U
}
class FirstName(val firstName: String)
class LastName(val lastName: String)
class Name: Into<FirstName>, Into<LastName> {
override fun into(): FirstName {
TODO("Not yet implemented")
}
override fun into(): LastName {
TODO("Not yet implemented")
}
}
This as stated before gives me a compilation error but i cannot understand why? These functions have different signatures and should therefore never clash with eachother
The second issue i had is related to the reverse operation, the From trait.
While in rust we can reference a static method on a trait directly with Trait::method_name such does not seem to be possible in Kotlin without having an instance that implements that same interface.
See this example:
interface From<T, Self: From<T, Self>> {
fun from(value: T): Self
}
class FirstName(val firstName: String)
class LastName(val lastName: String)
class Name(val name: String): From<FirstName, Name>, From<LastName, Name> {
override fun from(value: FirstName): Name {
TODO("Not yet implemented")
}
override fun from(value: LastName): Name {
TODO("Not yet implemented")
}
}
Obviously this suffers from the same problem as before, but now we also can’t actually call this method unless we have an instance of Name.
I believe it is possible to get around this second issue using reflection and doing some shenanigans but this would, without a doubt, be a hack.
Am i missing something?