Rescribet
01/15/2022, 5:02 PMto
method was for.
A method (or pair) to let the compiler automatically wire type conversions:
// 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
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>()
elizarov
02/09/2022, 8:39 AM