uhh, has there been any discussion about using som...
# stdlib
g
uhh, has there been any discussion about using something like
inline class
to simplify java's`compareTo` function? I was thinking that an
inline class
that's wrapping the results would be handy and do a lot for readability. If not, can we
typealias ComparisonResult = Int
and put some docs there? I feel like kotlin can do a lot to add sugar and/or lipstick to this pig in java.
👍 1
💯 1
e
I don't know if there's been discussion about it, but I agree that both
compareTo
and
indexOf
might be improved by wrappers around the various cases
👍 1
g
i think the place where I really want compiler help is with something like:
Copy code
when(left.compareTo(right)){
  LEFT_IS_FIRST -> ...
  BOTH_EQUAL -> ...
  RIGHT_IS_FIRST -> ...
}
I can do that using
in LEFT_IS_FIRST_RANGE
where thats
Int.Min .. -1
, but thats a couple extra objects and a little math I dont need, and the semantics dont really work out.
I guess this is actually synonymous with with the request for more operator support in the when clauses, because that's reasonably elegantly expressed as
Copy code
when(left.compareTo(right)){
  <= LEFT_IS_FIRST -> ...
  EQUAL -> ...
  >= RIGHT_IS_FIRST -> ...
}
but, then theres those cryptic
<=
and
>=
symbols, which betrays the abstraction for its ints. Alternatively, wouldnt many of these problems be solved with a
matches
operator?
Copy code
//given
typealias ComparisonResult = Int

// i could write
when(left.compareTo(right)){
  matches LEFT_IS_FIRST -> ...
  matches EQUAL -> ...
  matches RIGHT_IS_FIRST -> ...
}

// implemented with
object LEFT_IS_FIRST {
  operator fun matches(value: ComparisonResult): Boolean = value <= -1
}
But, again, surely there is a discussion somewhere in a keep/kotl.in issue about custom operators in
when
syntax
i also suspect that this would play really nicely with kotlin contracts, because the result could imply a bunch of things about the type-ee-ness of the argument
Copy code
object LEFT_IS_FIRST {
  operator fun matches(value: YourType): Boolean {
    contract {
      //bear with me ive forgotten the exact syntax here
      true implies valueNotNull 
        //tells body of when clause can assume 
        //the switch val isnt null
      false implies RIGHT_IS_FIRST or EQUAL 
        // give the compiler effective sealaed-class stuff
        // such that we dont need an `else` clause when
        // all three of these are covered
    }
  }
}
e
when (it) { in low..high -> }
is equivalent to
if (it >= low && it <= high)
, the range object isn't constructed (the compiler has a few special cases for specific types)
(but it only works for a literal range in that position, not if you had
val LEFT_IS_FIRST
)