博客
关于我
Java 8 中的 Lambda 表达式 vs. Kotlin 中的 Lambda
阅读量:290 次
发布时间:2019-03-01

本文共 2564 字,大约阅读时间需要 8 分钟。

Kotlin 函数式编程实例与高阶函数

代码示例

package com.easykotlin.lec02funfun sum1(x: Int, y: Int): Int {    return x + y}fun sum2(x: Int, y: Int) = x + y// sum2 函数字面量:匿名函数val sum3 = fun(x: Int, y: Int) = x + yval s3 = (fun(x: Int, y: Int) = x + y)(1, 1)val s32 = (fun(x: Int, y: Int) = x + y).invoke(1, 1)// Lambdaval sum4 = { x: Int, y: Int -> x + y }val s4 = { x: Int, y: Int -> x + y }(1, 1)val s42 = { x: Int, y: Int -> x + y }.invoke(1, 1)val sum5: (Int, Int) -> Int = { x, y -> x + y }// 高阶函数fun repeat(n: Int, body: () -> Unit) {    for (i in 1..n) {        body()    }}// 类型别名typealias A = (String) -> Inttypealias B = (Int) -> Booleantypealias C = (String) -> Booleanval length: A = { x -> x.length }val isOdd: B = { x -> x % 2 == 1 }// 高阶函数(复合函数)val filterOdd: C = { x -> isOdd(length(x)) }fun main(args: Array
) { val list = listOf("a", "abc", "abcbdf", "adsfeeff", "qwedddsssssdd") // 过滤出 list 中字符串长度是奇数的元素 val result = list.filter(filterOdd) println(result) repeat(3) { println("A") } // 1 + 2 + ... + 100 var sum = 0 var i = 1 repeat(100) { sum += i i++ } println("sum = $sum") sum1(1, 1) sum2(1, 1) sum3(1, 1) sum4(1, 1) sum5(1, 1) println("s3 = $s3") println("s32 = $s32") println("s4 = $s4") println("s42 = $s42")}

Java 8 对比

public void filter(Filter f, List
integerList) { for (Integer i : integerList) { if (f.test(i)) { System.out.println(i); } }}// 定义一个 SAMinterface Filter { boolean test(int x);}public void lambdaDemo() { filter((x) -> x % 2 == 1, Arrays.asList(1, 2, 3, 4, 5, 6, 7));}

Kotlin 优势

在 Kotlin 中,函数 f: (Int) -> Boolean 也是一种类型,可以像普通的参数变量一样,在函数入参中传递,当然也可以返回一个函数。

高阶函数示例

fun repeat(times: Int, body: () -> Unit) {    for (i in 0 until times) {        body()    }}fun main(args: Array
) { repeat(3, { println("A") }) repeat(3) { println("B") } var sum = 0 var i = 1 repeat(100) { sum += i i++ } println(sum)}

Function 接口

Function 接口类型只有一个调用方法:invoke()。

它包含三个动作:传入参数、处理参数、返回结果。

Kotlin 定义了 kotlin.jvm.functions 包里的接口,用于抽象所有函数类型。这些接口包括:

  • Function0:没有参数
  • Function1:有一个参数
  • Function2:有两个参数
  • ...
  • FunctionN:支持 23 个及以上参数

每个接口都继承自 Function,并定义了 invoke() 方法,通过重载括号操作符来传入参数和获取返回值。

匿名函数与 Lambda

val sum: (Int, Int) -> Int = fun(a: Int, b: Int) = a + b// 或者省略类型声明val sum = fun(a: Int, b: Int) = a + b// Lambda 表达式val sum = { a: Int, b: Int -> a + b }

这些函数对象会被编译为 Function2 类型的实现,可以通过 invoke() 方法调用,也可以直接使用括号操作符:

println(sum.invoke(1, 2))// 或者println(sum(1, 2))

小结

相比之下,Kotlin 对函数式编程的支持更加自然优雅。

转载地址:http://biea.baihongyu.com/

你可能感兴趣的文章
NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
查看>>
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>