Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

381
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda