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

274
Visualizações
Kotlin test if float is in open or semi open range

In Kotlin - is there an idiomatic way to test if a float is in a range where either (or both) the start or the end of the range is exclusive?

E.g something like

val inRange = 10.f in (0.0f until 20f)

I can't seem to find anything on this in the docs.

Update: How would one deal with semi-open ranges as well?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The until function creates the semi-closed integer (not float) range, where the left part is included and the right part is excluded. https://kotlinlang.org/docs/reference/ranges.html

There is closed float ranges support in Koltin https://kotlinlang.org/docs/reference/ranges.html#utility-functions

You may implement that yourself

data class OpenFloatRange(val from: Float, val to: Float)
infix fun Float.open(to: Float) = OpenFloatRange(this, to)
operator fun OpenFloatRange.contains(f: Float) = from < f && f < to

val inRange = 10f in (0.0f open 20f)

Here I use several tricks from Kotlin: https://kotlinlang.org/docs/reference/functions.html#infix-notation https://kotlinlang.org/docs/reference/operator-overloading.html#in

over 4 years ago · Santiago Trujillo Relatório

0

Inspired by what i selected as answer i came up with this solution, posting it here if anyone wants to reuse it.

class Range(private val fromInclusive: Boolean, val from: Float, val to: Float, private val toInclusive: Boolean) {

    infix fun contains(value: Float): Boolean {
        return when {
            fromInclusive && toInclusive -> value in from..to
            !fromInclusive && !toInclusive -> value > from && value < to
            !fromInclusive && toInclusive -> value > from && value <= to
            fromInclusive && !toInclusive -> value >= from && value < to
            else -> false
        }
    }
}

Usage: val inRange = Range(true, 0f, 10f, false) contains 5f

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