https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Michael de Kaste

01/17/2023, 10:40 AM
Hello; currently in our application, at some locations, we use a custom 'range' class with bounds like:
Copy code
date1..null // Range.BoundedLeft<LocalDateTime>
null..date2 // Range.BoundedRight<LocalDateTime>
date1..date2 // Range.Closed<LocalDateTime>
For this we made an operator fun on the rangeTo operator for comparable classes. This works fine for things like dates and custom classes. But if I want to use the rangeTo on an Int, there is no way for me to set the precedence of my own utility function over that of the construction of an IntRange, is this fixable? I know I can import my custom
rangeTo
as
somethingElse
, but I'd like to be able to do the following:
Copy code
val range: Range.Closed = 1..3
e

ephemient

01/17/2023, 10:49 AM
not sure this is a good idea. the compiler has built-in knowledge of the default
rangeTo
operator so that
Copy code
x in y..z
for (x in y..z)
do not construct range instances but are instead compiled as simple range checks and loops
m

Michael de Kaste

01/17/2023, 10:58 AM
I guess, if working with numbers specifically, I should make an extension function for nonnullable to nonnullable ranges. since
1..null
works fine
a

Adam S

01/17/2023, 11:08 AM
probably the easiest way is to create some extensions, so you can easily convert to your custom ‘range’ classes
Copy code
fun main() {
  val range: Range.Closed<Int> = (1..5).closed
}

val <T: Comparable<T>> ClosedRange<T>.closed
  get() = Range.Closed(this)
m

Michael de Kaste

01/17/2023, 11:23 AM
sadly, unless I make a compiler plugin, I can't make this exhaustive, but its a start
Copy code
when(date){
    in null..someRange -> "thing1"
    in someRange..someOtherRange -> "thing2"
    in someOtherRange..null -> "thing3"
}
e

ephemient

01/18/2023, 12:43 AM
in this case you can make it exhaustive and less repetitive
Copy code
when {
    date < someRange -> "thing1"
    date <= someOtherRange -> "thing2"
    else -> "thing3"
}
4 Views