Skip to Content
Head First Kotlin程序设计
book

Head First Kotlin程序设计

by Dawn Griffiths, David Griffiths
August 2020
Intermediate to advanced
483 pages
11h 24m
Chinese
China Machine Press
Content preview from Head First Kotlin程序设计
Lambda
和高阶函数
你现在的位置 4
339
lambda
作为函数参数
除了将
lambda
赋值给变量,你还可以使用一个或多个
lambda
作为
函数参数。这样做允许你将特定的行为传入更加通用的函数中
要了解这是如何工作的,我们将编写一个函数
convert
,它使用
一些公式转换通过
lambda
传入的
Double
对象,打印其结果并返
回。这允许我们将温度从摄氏转换为华氏,或是将体重从千克转
换为磅。如何转换将取决于我们在
lambda
参数中传入的公式。
我们将从定义函数参数开始。
fun convert(x: Double,
converter: (Double) -> Double ) : Double {
//Code to convert the Double
}
通过指定其名字和类型将
lambda
参数添加到
函数中
我们需要告诉
convert
函数两件事情,以便它将一个
Double
象转换为另一个:想要转换的
Double
对象,以及定义如何进行
转换的
lambda
表达式。因此,我们将为
convert
函数定义两个参
数:
Double
lambda
你可以使用与定义任何其他类型的函数参数相同的方式定义
lambda
参数:指定参数的类型和名字。我们将命名该
lambda
converter
,由于希望
lambda
Double
转换为
Double
,其
类型应该为
(Double)->Double
(一个接受
Double
参数并返回
Double
值的
lambda
)。
该函数定义如下(不包括函数体)。如你所见,它指定了两个参
数(名为 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

面向对象的思考过程(原书第5版)

面向对象的思考过程(原书第5版)

马特 魏斯费尔德
GraphQL 学习指南

GraphQL 学习指南

Eve Porcello, Alex Banks
前端架构设计

前端架构设计

Micah Godbolt

Publisher Resources

ISBN: 9787111662358