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的语法的各种简化也不会超过这一点
posted @   xuchaoxin1375  阅读(5)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2023-04-01 ML@python@稀疏矩阵的存储和表示@CSR格式
2023-04-01 从键盘输入若干 整数(零表示结束), 统计出 数据个数, 以及最大值、最小值和平均值。
2022-04-01 linux_系统编程系统库调用和函数所在头文件的查询/apropos获取按功能查找命令/查找头文件所在目录
点击右上角即可分享
微信分享提示