3

Is it possible to apply an extensions function to several types at once? Something link this

fun <Double || Float>.toString(): String
yaugenka
  • 2,602
  • 2
  • 22
  • 41
  • 2
    No, this is not possible. Anyway, it wouldn't be very useful, as you rarely can perform same operations with entirely different types. – broot Jan 09 '22 at 13:32
  • The only way this works is, when all of the types share a common supertype. For example, you could add an extension function to `Number`. However, as pointed out by @broot, this might not prove very useful. The syntax you suggest looks a lot like union types, which might be supported in a [future version of Kotlin](https://discuss.kotlinlang.org/t/union-types/77). If you're in control of the type hierarchy, you may want to look at `sealed interfaces / classes`, which is probably the closest you'll get to union types with the current version of Kotlin. – Endzeit Jan 09 '22 at 13:44

0 Answers0