loicdescotte
5/16/2016 - 7:28 PM

Kotlin : compose futures of nullables

Kotlin : compose futures of nullables

    @Test
    fun combineNullable() {
        fun giveInt(x: Int):Int? = x+1
        
        fun giveInt2(x: Int):Int? = x+2
        
        fun combine(x: Int): Int? = giveInt(x)?.let { giveInt2(it) }
        
        assertEquals(combine(1),4)
    }

    @Test
    fun combineFuture(){

        fun giveInt(x:Int): CompletableFuture<Int> {
            return CompletableFuture.supplyAsync({ x+1 })
        }

        fun giveInt2(x:Int): CompletableFuture<Int> {
            return CompletableFuture.supplyAsync({ x+2 })
        }

        fun combine(x: Int): CompletableFuture<Int> {
            return giveInt(x).thenCompose({ giveInt2(it) })
        }

        assertEquals(combine(1).get(),4)
    }

    @Test
    fun combineFutureOfNullable(){
        fun giveInt(x:Int): CompletableFuture<Int?> = CompletableFuture.supplyAsync({ x+1 })

        fun giveInt2(x:Int): CompletableFuture<Int?> = CompletableFuture.supplyAsync({ x+2 })
        
        fun combine (x: Int): CompletableFuture<Int?> = giveInt(x).thenCompose({ it?.let {giveInt2(it) }})

        assertEquals(combine(1).get(),4)
    }