Alternative typing in a constructor/parameter

Sometimes I need to make redundant functions which just takes two different types as arguments, with a very minimal conversion between them, which adds a lot of redundancy, so I propose: alternative typing.

The syntax could be something like this

fun timeTwo(number: Int[(String) -> it.toInt(), (Double) -> it.toInt()] = number * 2

Which could easily be broken apart by the compiler into separate constructor/methods, and removes a lot of redundancy.

1 Like

this join the union type discussion i think

fun timeTwo(number: Int|String|Double) {
  if (number is Int) {
    return number * 2
  }
  else {
      return number.toInt()
  }
}
1 Like

I think this is much different than OP’s suggestion. Union types allow to pass multiple types and recognize them in runtime. OP suggested a syntactic sugar to allow to invoke functions with alternative param types that will be automatically converted to required ones. This is similar to default param values where missing params are replaced with default values.

I personally like the idea, although the syntax for it will be the tricky part. Also, we might need @JvmOverloads or something similar for it.

1 Like