3

below is my Kotlin extension function :

infix fun Int.send(data: String) {
    MsgSendUtils.sendStringMsg(
        this,
        data
    )
}

called like this :

 8401 send "hi"

and my requirement is : the caller must greater than 8400 .

How can i achieve that ?

Thanks !

Hui He
  • 77
  • 3

1 Answers1

3

In theory, you can use the syntax @receiver:IntRange(from = 8400) to apply an annotation to the receiver of a function:

infix fun @receiver:IntRange(from = 8400) Int.send(data: String) {
    MsgSendUtils.sendStringMsg(this, data)
}

However, this doesn't seem to trigger the Android Lint error as you would expect. This is probably a missing feature in the linter itself when inspecting Kotlin code.

A workaround would be to declare the function differently (using this value as parameter instead of receiver):

fun send(@IntRange(from = 8400) id: Int, data: String) {
    MsgSendUtils.sendStringMsg(id, data)
}
// or
fun String.sendTo(@IntRange(from = 8400) id: Int) {
    MsgSendUtils.sendStringMsg(id, this)
}

Otherwise the best you could do in pure Kotlin would be to check the value at runtime:

infix fun Int.send(data: String) {
    require(this >= 8400) { "This value must be greater than 8400" }
    MsgSendUtils.sendStringMsg(this, data)
}

Note that, depending on what this value represents, I would advise using a more specific type instead of Int. For example, if your Int represents an ID, maybe you should instead declare a value class wrapping this integer. You can then enforce the constraints at construction time (still at runtime, but it's less error-prone).

This approach would also avoid polluting auto-completion on all integers, which can be pretty annoying on a big project given how specific this function is.

Joffrey
  • 32,348
  • 6
  • 68
  • 100