Created
January 17, 2016 08:48
-
-
Save jmatsu/711e36eee3722505bc94 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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