Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

380
Views
How can I use annotation @IntRange for Kotlin extension function for Integer

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 !

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!