Typealiases for ranges


#1

For example:

typealias DayOfWeek = 1..7
typealias Percent = 0d..100d
typealias Grade = 'A'..'D'

enum class Difficulty { VERY_EASY, EASY, NORMAL, HARD, VERY_HARD}
typealias EasyDifficulty = Difficulty.VERY_EASY..Difficulty.EASY

val pecentDone: Percent = 99.9d
val compilationErrorHere: Percent = 100.1d

typealias Workdays: DayOfWeek = 1..5

fun currentDay() = 5

val today = currentDay()

fun main(args: Array<String>) {
    // as with any range
    if (today !in Workdays) println(":)")
}

Is (or will) it possible to do something similar in Kotlin?


#2

Ranges in Kotlin are not types, so no typealias for them. Making them into proper types is… complicated.


#3

Sadly then.

Delphi has such a feature (SubRanges):

 type
   TSmallNum = 0..9;
 var
   smallNum : TSmallNum;
 begin
   smallNum := 5;    // Allowed
   smallNum := 10;   // Not allowed
   smallNum := -1;   // Not allowed
 end;

Compiler-time checks could save a lot of typing like this:

fun foo(bar: Int) {
	if (bar < 0 || bar > 9) {
		throw IllegalArgumentException("Invalid bar: ${bar}")
	}
	...
}

It would be nice to have it at compile time.


#4

While I think that range types are interesting, it is a significant language feature. They also have limited value when not combined with range checks on each update. There are various questions on coercion as well - and how do ranges interact with the comparison operators?