Kotlin provides many features by convention, like operator overloading; however, there is no way for a method to specify it only accepts objects which impliments a given operator (or set of operators). For example if I wanted to write a generic method which requires its arguments implement basic math operations plus(+) and minus(-) there is no way to specify this.
“By convention” operator overloading is great, it just works; however, in this case there is no super interface to represent the objects support basic math, the function cannot be written with generics. The only option is to rewriting the same code for different types.
A solution is to allow duck typing, or more duck casting. For example
trait BasicMath<T>: Comparable<T> {
fun plus( b: T) :T
fun minus( b: T): T
}
fun <T:BasicMath<T>> subtractTo(a: T, b: T, limit: T) : T {
val value = a - b
if (value < limit) {
return limit
} else {
return value
}
}
//and to use the function, compiler does magic
val result = subtractTo(1,2,0)
//or you do it for it
val r2 = subtractTo(3 as BasicMath<Int>, 2 as BasicMath<Int>, 0 as BasicMath<Int>)
This comes down to allowing forcefully casting an object to a trait it did not impliment but does satisfy.
Thoughts:
- Syntax: what is perposed looks bad on the second method call?
- Many Traits: how could this be supported?
- Other ways of doing this?
- Cyclon: supports type intersections and unions, maybe something like that?
Thanks
- Matt