Skip to content

Instantly share code, notes, and snippets.

@jmatsu
Created January 17, 2016 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmatsu/711e36eee3722505bc94 to your computer and use it in GitHub Desktop.
Save jmatsu/711e36eee3722505bc94 to your computer and use it in GitHub Desktop.
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class IntRestrictedProperty(minValue : Int, maxValue : Int, private var curValue:Int = 0) : ReadWriteProperty<Any?, Int> {
val valueRange = IntRange(minValue, maxValue)
override fun getValue(thisRef: Any?, prop: KProperty<*>): Int = curValue
override fun setValue(thisRef: Any?, prop: KProperty<*>, value: Int) {
curValue = valueRange.clamp(value)
}
fun IntRange.clamp (value:Int) : Int =
when(true) {
contains(value) -> value
value < start -> start
else -> endInclusive
}
}
class ExamResult(val subject:String) {
var point: Int by IntRestrictedProperty(minValue = 0, maxValue = 100)
override fun toString(): String = "${subject} : ${point}"
}
fun main(args: Array<String>) {
val japanese = ExamResult("国語")
japanese.point = -10
println(japanese) // 国語 : 0
val english = ExamResult("英語")
english.point = 110
println(english) // 英語 : 100
// val del = IntRestrictedProperty(minValue = 0, maxValue = 100)
// println(del.curValue)
// del.curValue = 1020
// println(del.curValue)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment