Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

382
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda