Is there a way to use Java 8 functional interfaces on Android API below 24?

前端 未结 4 1309
梦如初夏
梦如初夏 2021-01-01 10:26

I can use retrolambda to enable lambdas with Android API level <24. So this works

myButton.setOnClickListener(view -> Timber.d(\"Lambdas work!\"));
         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 11:17

    Android support library(AndroidX) now has Consumer and Supplier:

    • androidx.core.util.Consumer (appears in androidx.appcompat:appcompat:1.0.2)
    • androidx.core.util.Supplier (appears in androidx.appcompat:appcompat:1.1.0-alpha01)

    sadly only these two interfaces gets added as of writing.

    Now we have Kotlin, it doesn't require you to specify the functional interface explicitly:

        fun test() {
            val text = withPrintStream {
                it.println("Header bla bla ")
                it.printf("%s, %s, %s,", "a", "b", "c").println()
            }
        }
    
        // Equivalent to the following code in Java:
        //     Consumer action;
        //     action.accept(ps);
        fun withPrintStream(action: (PrintStream) -> Unit): String {
            val byteArrayOutputStream = ByteArrayOutputStream()
            val ps = PrintStream(byteArrayOutputStream)
            action(ps)
            ps.flush()
            return byteArrayOutputStream.toString()
        }
    

提交回复
热议问题