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

273
Views
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 answers
Answer question

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 Report

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 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!