41 lines
1.1 KiB
Kotlin
41 lines
1.1 KiB
Kotlin
|
|
|
|
fun main() {
|
|
testMap()
|
|
testFilter()
|
|
testFold()
|
|
shouldHandleNullableTypes()
|
|
}
|
|
|
|
fun testMap() {
|
|
assertEquals(Option.just(3).map { it * 2 }.map { "$it" }.getOrNull(), "6")
|
|
assertEquals(Option.just(listOf(1)).map { it.first() }.getOrNull(), 1)
|
|
assertEquals(Option.none<Int>().map { error("Should not be executed") }.getOrNull(), null)
|
|
}
|
|
|
|
fun testFilter() {
|
|
assertEquals(Option.just(6).filter { it > 5 }.getOrNull(), 6)
|
|
assertEquals(Option.just(6).filter { it < 5 }.getOrNull(), null)
|
|
}
|
|
|
|
fun testFold() {
|
|
assertEquals(Option.just(2).map { it * 2 }.fold({ it / 2 }, { error("Should not be executed") }), 2)
|
|
assertEquals(Option.none<Int>().fold({ error("Should not be executed") }, { 2 }), 2)
|
|
}
|
|
|
|
fun shouldHandleNullableTypes() {
|
|
assertEquals(Option.just<Int?>(null).map { it ?: 5 }.getOrNull(), 5)
|
|
assertEquals(
|
|
Option.just<List<String>>(emptyList())
|
|
.map { it.firstOrNull() }
|
|
.fold({ it }, { error("Should not be executed") }),
|
|
null
|
|
)
|
|
}
|
|
|
|
private fun <T> assertEquals(x: T, y: T) {
|
|
if (x != y) {
|
|
error("$x was not equal to $y")
|
|
}
|
|
}
|