I was looking at the <KT-43871> concerns section, ...
# language-proposals
r
I was looking at the KT-43871 concerns section, which reminded me of what I originally thought the
to
method was for. A method (or pair) to let the compiler automatically wire type conversions:
Copy code
// I'm not well versed in Kotlin interfaces
interface Convertible<reified A : Any, reified B : Any> {
    inline fun from<A>(val it: A): B
    inline fun <http://A.to|A.to><B>(): B
}

// or more explicit
convert fun A.B(val it: B): A
Copy code
data class Point(val x: Int, val y: Int)

/** Creates a Point from an IntArray */
fun Point.from<IntArray>(val it: IntArray) = Point(it[0], it[1])
fun <http://Point.to|Point.to><IntArray>() = intArrayOf(this.x, this.y)

fun draw(point: Point)

draw(Point(0, 1))
draw(listOf(0, 1) -> draw(Point(it[0], it[1]))
Where the compiler will check the existence of a matching conversion and apply it automatically. Note that it should only be added by developers on types with clear semantics, e.g. String should be avoided in most use cases. Adding inline classes for more specific behaviour might be helpful (i.e.
HumanReadableString
and
SerializableString
) Other use-cases: • Java interop,
<http://java.time.Instant.to|java.time.Instant.to><kotlinx.datetime.Instant>()
• Serialization, ie
MyClass.from<String>()
• Automatic API upgrades,
<http://V1Object.to|V1Object.to><V2Object>()
e
This is called "implicit conversion" and it is a feature that is extremely hard to design properly without making the code in the langauge very error-prone.