0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

上限、下限つきの値を生成するクラス(ジェネリクス対応)[kotlin]

Last updated at Posted at 2017-03-30

キーワード:Range、制限、リミット,limit
#目的

GoogleGuavaのRangeクラスのように範囲内に入っているかをBooleanで返すのではなく、値を変化させたときに

上限を超えた場合->上限値
下限を下回った場合->下限値

とするようなクラスが欲しかったのでジェネリクス対応で作った。
同じ初期値、上限、下限の値を用意したいときに有効..かな

#コード


fun main(args : Array<String>){
    val limitedValue = LimitedValue<Int>(initialValue = 1,MAX_VALUE = 10,MIN_VALUE = 0)
    limitedValue.value = 100
    println(limitedValue.value)

    val limitedDoubleFactory = {LimitedDouble(
            initialValue = 10.0,
            MAX_VALUE    = 100.0,
            MIN_VALUE    = 0.0,
            calcMethod   = fun Double.(others  : DoubleArray) : Double = this + others.sum())}
    val limitedDouble = limitedDoubleFactory.invoke()
    println(limitedDouble.setValueProcessArgumentsInTheRange(10.0,20.0))
}

class LimitedDouble private constructor(private val limitedValue: LimitedValue<Double>,private val calcMethod : Double.(DoubleArray)->(Double)) {

    constructor(initialValue: Double,MAX_VALUE: Double,MIN_VALUE: Double,calcMethod: Double.(DoubleArray) -> Double)
            : this(limitedValue = (LimitedValue(initialValue, MAX_VALUE,MIN_VALUE)), calcMethod   = calcMethod )
    fun setValueProcessArgumentsInTheRange(vararg values : Double) : Double = calcMethod(limitedValue.value,values)

}

class LimitedValue<T : Comparable<T>>(private val initialValue : T,private val MAX_VALUE : T,private val MIN_VALUE : T){
    var value : T = initialValue
        set(value) = when {
            value > MAX_VALUE -> field = MAX_VALUE
            value < MIN_VALUE -> field = MIN_VALUE
            else -> field = value
        }

    init {
        require(MIN_VALUE < MAX_VALUE){"MAX_VALUE should be bigger than MIN_VALUE"}
        require(initialValue <= MAX_VALUE){"Initial Value should be smaller than MAX_VALUE"}
        require(initialValue >= MIN_VALUE){"Initial Value should be bigger  than MIN_VALUE"}
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?