BAEL-2760

This commit is contained in:
Rodrigo Graciano 2019-03-10 20:34:19 -04:00
parent b98294aaed
commit da2f95bfa3
2 changed files with 97 additions and 0 deletions

View File

@ -0,0 +1,56 @@
package com.baeldung.range
import java.lang.IllegalStateException
class CustomColor(val rgb: Int): Comparable<CustomColor> {
override fun compareTo(other: CustomColor): Int {
return this.rgb.compareTo(other.rgb)
}
operator fun rangeTo(that: CustomColor) = ColorRange(this,that)
operator fun inc(): CustomColor {
return CustomColor(rgb + 1)
}
init {
if(rgb < 0x000000 || rgb > 0xFFFFFF){
throw IllegalStateException("RGB must be between 0 and 16777215")
}
}
override fun toString(): String {
return "CustomColor(rgb=$rgb)"
}
}
class ColorRange(override val start: CustomColor,
override val endInclusive: CustomColor) : ClosedRange<CustomColor>, Iterable<CustomColor>{
override fun iterator(): Iterator<CustomColor> {
return ColorIterator(start, endInclusive)
}
}
class ColorIterator(val start: CustomColor, val endInclusive: CustomColor) : Iterator<CustomColor> {
var initValue = start
override fun hasNext(): Boolean {
return initValue <= endInclusive
}
override fun next(): CustomColor {
return initValue++
}
}
fun main(args: Array<String>) {
val a = CustomColor(0xABCDEF)
val b = CustomColor(-1)
val c = CustomColor(0xABCDFF)
for(color in a..c){
println(color)
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.range
import org.junit.Test
import java.lang.IllegalStateException
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class CustomColorTest {
@Test
fun testInvalidConstructor(){
assertFailsWith(IllegalStateException::class){
CustomColor(-1)
}
}
@Test
fun assertHas10Colors(){
assertTrue {
val a = CustomColor(1)
val b = CustomColor(10)
val range = a..b
for(cc in range){
println(cc)
}
range.toList().size == 10
}
}
@Test
fun assertContains0xCCCCCC(){
assertTrue {
val a = CustomColor(0xBBBBBB)
val b = CustomColor(0xDDDDDD)
val range = a..b
range.contains(CustomColor(0xCCCCCC))
}
}
}