Skip to content

Commit da2f95b

Browse files
BAEL-2760
1 parent b98294a commit da2f95b

2 files changed

Lines changed: 97 additions & 0 deletions

File tree

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.baeldung.range
2+
3+
import java.lang.IllegalStateException
4+
5+
class CustomColor(val rgb: Int): Comparable<CustomColor> {
6+
7+
override fun compareTo(other: CustomColor): Int {
8+
return this.rgb.compareTo(other.rgb)
9+
}
10+
11+
operator fun rangeTo(that: CustomColor) = ColorRange(this,that)
12+
13+
operator fun inc(): CustomColor {
14+
return CustomColor(rgb + 1)
15+
}
16+
17+
init {
18+
if(rgb < 0x000000 || rgb > 0xFFFFFF){
19+
throw IllegalStateException("RGB must be between 0 and 16777215")
20+
}
21+
}
22+
23+
override fun toString(): String {
24+
return "CustomColor(rgb=$rgb)"
25+
}
26+
}
27+
class ColorRange(override val start: CustomColor,
28+
override val endInclusive: CustomColor) : ClosedRange<CustomColor>, Iterable<CustomColor>{
29+
30+
override fun iterator(): Iterator<CustomColor> {
31+
return ColorIterator(start, endInclusive)
32+
}
33+
}
34+
35+
class ColorIterator(val start: CustomColor, val endInclusive: CustomColor) : Iterator<CustomColor> {
36+
37+
var initValue = start
38+
39+
override fun hasNext(): Boolean {
40+
return initValue <= endInclusive
41+
}
42+
43+
override fun next(): CustomColor {
44+
return initValue++
45+
}
46+
}
47+
48+
fun main(args: Array<String>) {
49+
val a = CustomColor(0xABCDEF)
50+
val b = CustomColor(-1)
51+
val c = CustomColor(0xABCDFF)
52+
53+
for(color in a..c){
54+
println(color)
55+
}
56+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.range
2+
3+
import org.junit.Test
4+
import java.lang.IllegalStateException
5+
import kotlin.test.assertFailsWith
6+
import kotlin.test.assertTrue
7+
8+
class CustomColorTest {
9+
10+
@Test
11+
fun testInvalidConstructor(){
12+
assertFailsWith(IllegalStateException::class){
13+
CustomColor(-1)
14+
}
15+
}
16+
17+
@Test
18+
fun assertHas10Colors(){
19+
assertTrue {
20+
val a = CustomColor(1)
21+
val b = CustomColor(10)
22+
val range = a..b
23+
for(cc in range){
24+
println(cc)
25+
}
26+
range.toList().size == 10
27+
}
28+
}
29+
30+
@Test
31+
fun assertContains0xCCCCCC(){
32+
assertTrue {
33+
val a = CustomColor(0xBBBBBB)
34+
val b = CustomColor(0xDDDDDD)
35+
val range = a..b
36+
range.contains(CustomColor(0xCCCCCC))
37+
}
38+
}
39+
40+
}
41+

0 commit comments

Comments
 (0)