Hello; currently in our application, at some locat...
# getting-started
m
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
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
I guess, if working with numbers specifically, I should make an extension function for nonnullable to nonnullable ranges. since
1..null
works fine
a
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
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
in this case you can make it exhaustive and less repetitive
Copy code
when {
    date < someRange -> "thing1"
    date <= someOtherRange -> "thing2"
    else -> "thing3"
}