kotlin函数式编程精简写法的过程探索学习实例
文章目录
introduction:
when I learning the Android development techniques,I often access the Google Android Development website ,And I fond there are lots of kotlin example codes use the very tidy writing;
but I was not understood well,so I study the related knowledge about kotlin lambda programming techniques and the simplied writting and the regularities(the functional api programming)
example code:
Thread {
println("Thread is running")
}.start()
original version:
from java:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread is running");
}
}).start();
to kotlin:
Thread(object : Runnable {
override fun run() {
println("Thread is running")
}
}).start()
simplified 1:
Thread(Runnable {
println("Thread is running")
}).start()
the Runnable (it’s a signal abstract method Interface) instance is the only one(There is one and only one Java single abstract method interface parameter) (without other singal abstract method Interface instance as parameter) of the Thread constructor to instantiate a instance,
as the kotlin syntax,we can omit the Interface name:Runnable;
simplified 2:
Thread({
println("Thread is running")
}).start()
what’s more , the Thread() method has no other parameter,then the parenthesis could be omit too:
the last version:
Thread {
println("Thread is running")
}.start()
- 对函数式api编程:
函数式编程的要点在于,将一段代码作为参数传递(这段代码可以在不引发歧义的情况下,达到和传入一个实例对象一样的效果,不引发歧义的情况下,还可以进一步简化语法)
在很多种编程语言中都有lambda(或者叫lambda函数)这一概念;
比如kotlin的lambda表达式(代码段)会被处理成一个对象,而不能完全等同于普通函数的概念(但不管语法如何,都在于逻辑(代码段)参数是否满足需要) - kotlin对于kotlin的语法的各种简化也不会超过这一点

浙公网安备 33010602011771号