Home > Back-end >  Kotlin short literal pre/postfix?
Kotlin short literal pre/postfix?

Time:12-04

The following code throws an error that == cannot be applied between int and short.

if(shortVal == 3)

Does Kotlin have a way to denote that a numeric literal is a short, something like 3S?

CodePudding user response:

There is no functionality like that in the standard library, as far as I know. But you're still free to implement a functionality like that on your own, e.g. using Kotlin's extension properties.

val Int.s: Short
    get() = toShort()

val i: Int = 3
val s: Short = 3.s

CodePudding user response:

You could also create an infix function instead of ==. I called it eq

infix fun Short.eq(i: Int): Boolean = this == i.toShort()

And you can use it like this

if(shortVal eq 3)
  • Related