阅读完需:约 25 分钟
高阶函数
高阶函数(高阶函数)是一个接受函数作为参数或返回函数或可以同时执行这两个函数的函数。 意味着,可以将函数作为参数传递给其他函数,而不是将Int
,String
或其他类型作为参数传递给函数。
在这里传了一个名字为block的函数,这个函数的参数为空,返回值也是空
常见的高阶函数
inline: Kotlin中的一个关键字,用来修饰function,那么这个function就被称作inline function(内联函数)。
fun myFun(org: String,portal: String, fn: (String,String) -> String): Unit {
val result = fn(org,portal)
println(result)
}
在上面的例子中,使用三个参数定义了一个函数myFun()
。 第一个和第二个参数取String
,第三个参数是有两个String
类型参数的函数。 参数String -> String
类型表示函数将String
作为输入并将输出作为字符串类型返回。
要调用上面的函数,可以传递函数文字或lambda
。
fun myFun(org: String,portal: String, fn: (String,String) -> String): Unit {
val result = fn(org,portal)
println(result)
}
fun main(args: Array<String>){
val fn:(String,String)->String={org,portal->"$org develop $portal"}
myFun("yiibai.org","yiibai.com",fn)
}
执行上面示例代码,得到以下结果
yiibai.org develop yiibai.com
上面的高阶函数也可以用另一种方式调用,如下面提到的main()
函数中的代码:
myFun("yiibai.org","yiibai.com",{org,portal->"$org develop $portal"})
高阶函数的调用
高阶函数的调用和之前的函数调用没什么区别
kotlin 的函数类型自动推导
高阶函数例子:
fun main() {
cost {
val fibonacciNext = fibonacci()
for (i in 0..10) {
println(fibonacciNext())
}
}
// region +折叠
val intArray = IntArray(5){ it + 1 }
intArray.forEach {
println(it)
}
intArray.forEach(::println)
intArray.forEach {
println("Hello $it")
}
//endregion
}
//region +折叠
fun needsFunction(block: () -> Unit) {
block()
}
fun returnsFunction(): () -> Long {
return { System.currentTimeMillis() }
}
//endregion
fun cost(block: () -> Unit) {
val start = System.currentTimeMillis()
block()
println("${System.currentTimeMillis() - start}ms")
}
fun fibonacci(): () -> Long {
var first = 0L
var second = 1L
return {
val next = first + second
val current = first
first = second
second = next
current
}
}
解析例子:
fun twoAndThree(operation: (Int, Int) -> Int) {
// 调用函数类型的参数
val result = operation(2, 3)
println("The result is $result")
}
twoAndThree { i, j -> i + j }
// The result is 5
twoAndThree { i, j -> i * j }
// The result is 6
调用作为参数的函数和调用普通函数的语法是一样的:把括号放在函数名后,并把参数放在括号中。
高阶函数拆开来写就是两个单独的函数,唯一的区别就是函数的规则不同
fun twoAndThree() {
// 调用函数类型的参数
val result = operation(2, 3)
val result2 = operation2(2, 3)
println("The result is $result $result2")
}
fun operation(int1: Int,int2: Int):Int{
return int1 + int2
}
fun operation2(int1: Int,int2: Int):Int{
return int1 * int2
}
twoAndThree()
filter函数例子:
fun String.filter(predicate: (Char) -> Boolean): String {
val sb = StringBuilder()
for (index in 0 until length) {
val element = get(index)
// 调用作为参数传递给"predicate"函数
if (predicate(element)) sb.append(element)
}
return sb.toString()
}
// 传递一个lambda,作为predicate参数
println("ab3d".filter { c -> c in 'a'..'z' })
// abd
这个例子和上面也是一样的道理,都是可以看作是拆分的函数,合在了一起只不过是规则不同。
joinToString 例子:
fun <T> Collection<T>.joinToString(
separator: String = ", ",
prefix: String = "",
postfix: String = "",
// 声明一个以lambda为默认值的函数类型的参数
transform: (T) -> String = { it.toString() }
): String {
val result = StringBuilder(prefix)
for ((index, element) in this.withIndex()) {
if (index > 0) result.append(separator)
// 调用作为实参传递给 "transform" 形参的函数
result.append(transform(element))
}
result.append(postfix)
return result.toString()
}
val list = listOf("A", "B", "C")
// 传递一个lambda作为参数
println(list.joinToString { it.toLowerCase() })
// a, b, c
在这个例子中可以很清楚的看到高阶函数的运用和调用者赋予的规则,以及默认函数的用法。
返回函数的函数
函数除了当参数传入还可以当结果返回,这就是返回函数
enum class Delivery {
STANDARD, EXPEDITED
}
class Order(val itemCount: Int)
fun getShippingCostCalculator(
delivery: Delivery
): (Order) -> Double { // 声明一个返回函数的函数
if (delivery == Delivery.EXPEDITED) {
// 返回lambda
return { order -> 6 + 2.1 * order.itemCount }
}
return { order -> 1.2 * order.itemCount }
}
// 将返回的函数保存在变量中
val calculator = getShippingCostCalculator(Delivery.EXPEDITED)
// 调用返回的函数
println("shipping costs ${calculator(Order(3))}")
// shipping costs 12.3
回到上面的解析例子也是可以换一种写法:
fun twoAndThree(int: Int,int1: Int,int2: Int) {
// 调用函数类型的参数
val result = operation(int)
println("The result is ${result(int1,int2)}")
}
fun operation(int: Int):(Int, Int)->Int{
return when(int){
1 -> { int1,int2->int1 + int2}
0-> { int1,int2-> int1 * int2}
else -> { int1,int2-> int1 - int2}
}
}
twoAndThree(0,2,3)
实用的高阶函数
Filter
fun main(args: Array<String>) {
val arrays = (0..10)
var arrays1 = (2..8)
/**
* 获得基数
*/
arrays.filter { it % 2 == 1 }.forEach(::println)
/**
* takeWhile只获取满足条件之前的数据
*/
arrays1.takeWhile { it % 2 == 0 }.forEach(::println)
}
Let、apply、with、use
@Pojos
data class WorlderCup(val name: String, val old: Int, val host: String) {
fun getTeamCount() {
println("${name}参赛队伍一共32支")
}
}
fun main(args: Array<String>) {
/**
* 使用let正对于某个对象进行操作
* 返回=》WorlderCup(name=俄罗斯世界杯, old=84, host=俄罗斯)
*/
worldercup().let {
println(it)
}
//返回=>10000
100.let { println(it * 100) }
/**
* apply相当于this
* 返回=>俄罗斯世界杯参赛队伍一共32支
*/
worldercup().apply {
getTeamCount()
}
/**
* with把对象和this合并到一起
*/
with(worldercup(), {
println(name)
})
/**
* 使用with函数返回=》阿根廷不要为我哭泣
*/
var bufferread = BufferedReader(FileReader("worldcup.txt"))
with(bufferread) {
var line: String
while (true) {
line = readLine() ?: break
print(line)
}
close()
}
/**
* 读取BuffererReader
*/
// println(bufferread.readText())
/**
* 返回的对象有closeable方法的话 调用use 就不用手动调用close方法
*/
BufferedReader(FileReader("worldcup.txt")).use {
var line: String
while (true) {
line = it.readLine() ?: break
print(line)
}
}
}
fun worldercup(): WorlderCup {
return WorlderCup("俄罗斯世界杯", 84, "俄罗斯")
}
实用高阶函数具体用法
let — 内联扩展函数
let扩展函数的实际上是一个作用域函数,当你需要去定义一个变量在一个特定的作用域范围内,let函数的是一个不错的选择;let函数另一个作用就是可以避免写一些判断null的操作。
- let函数的使用的一般结构
object.let{
it.todo()//在函数体内使用it替代object对象去访问其公有的属性和方法
...
}
//另一种用途 判断object为null的操作
object?.let{//表示object不为null的条件下,才会去执行let函数体
it.todo()
}
- let函数底层的inline扩展函数+lambda结构
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
- let函数inline结构的分析
从源码let函数的结构来看它是只有一个lambda函数块block作为参数的函数,调用T类型对象的let函数,则该对象为函数的参数。在函数块内可以通过 it 指代该对象。返回值为函数块的最后一行或指定return表达式。
- let函数的kotlin和Java转化
//kotlin
fun main(args: Array<String>) {
val result = "testLet".let {
println(it.length)
1000
}
println(result)
}
//java
public final class LetFunctionKt {
public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
String var2 = "testLet";
int var4 = var2.length();
System.out.println(var4);
int result = 1000;
System.out.println(result);
}
}
- let函数适用的场景
场景一: 最常用的场景就是使用let函数处理需要针对一个可null的对象统一做判空处理。
场景二: 然后就是需要去明确一个变量所处特定的作用域范围内可以使用
- let函数使用前后的对比
没有使用let函数的代码是这样的,看起来不够优雅
mVideoPlayer?.setVideoView(activity.course_video_view)
mVideoPlayer?.setControllerView(activity.course_video_controller_view)
mVideoPlayer?.setCurtainView(activity.course_video_curtain_view)
使用let函数后的代码是这样的
```
mVideoPlayer?.let {
it.setVideoView(activity.course_video_view)
it.setControllerView(activity.course_video_controller_view)
it.setCurtainView(activity.course_video_curtain_view)
}
```
with — 内联函数
- with函数使用的一般结构
with(object){
//todo
}
- with函数底层的inline扩展函数+lambda结构
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
- with函数inline结构的分析
with函数和前面的几个函数使用方式略有不同,因为它不是以扩展的形式存在的。它是将某对象作为函数的参数,在函数块内可以通过 this 指代该对象。返回值为函数块的最后一行或指定return表达式。
可以看出with函数是接收了两个参数,分别为T类型的对象receiver和一个lambda函数块,所以with函数最原始样子如下:
```
val result = with(user, {
println("my name is $name, I am $age years old, my phone number is $phoneNum")
1000
})
```
但是由于with函数最后一个参数是一个函数,可以把函数提到圆括号的外部,所以最终with函数的调用形式如下:
```
val result = with(user) {
println("my name is $name, I am $age years old, my phone number is $phoneNum")
1000
}
```
- with函数的kotlin和Java转化
//kotlin
fun main(args: Array<String>) {
val user = User("Kotlin", 1, "1111111")
val result = with(user) {
println("my name is $name, I am $age years old, my phone number is $phoneNum")
1000
}
println("result: $result")
}
//java
public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
User user = new User("Kotlin", 1, "1111111");
String var4 = "my name is " + user.getName() + ", I am " + user.getAge() + " years old, my phone number is " + user.getPhoneNum();
System.out.println(var4);
int result = 1000;
String var3 = "result: " + result;
System.out.println(var3);
}
- with函数的适用的场景
适用于调用同一个类的多个方法时,可以省去类名重复,直接调用类的方法即可,经常用于Android中RecyclerView中onBinderViewHolder中,数据model的属性映射到UI上
- with函数使用前后的对比
没有使用kotlin中的实现
```
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
ArticleSnippet item = getItem(position);
if (item == null) {
return;
}
holder.tvNewsTitle.setText(StringUtils.trimToEmpty(item.titleEn));
holder.tvNewsSummary.setText(StringUtils.trimToEmpty(item.summary));
String gradeInfo = "难度:" + item.gradeInfo;
String wordCount = "单词数:" + item.length;
String reviewNum = "读后感:" + item.numReviews;
String extraInfo = gradeInfo + " | " + wordCount + " | " + reviewNum;
holder.tvExtraInfo.setText(extraInfo);
...
}
```
kotlin的实现
```
override fun onBindViewHolder(holder: ViewHolder, position: Int){
val item = getItem(position)?: return
with(item){
holder.tvNewsTitle.text = StringUtils.trimToEmpty(titleEn)
holder.tvNewsSummary.text = StringUtils.trimToEmpty(summary)
holder.tvExtraInf.text = "难度:$gradeInfo | 单词数:$length | 读后感: $numReviews"
...
}
}
```
run — 内联扩展函数
- run函数使用的一般结构
object.run{
//todo
}
- run函数的inline+lambda结构
@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R = block()
- run函数的inline结构分析
run函数实际上可以说是let和with两个函数的结合体,run函数只接收一个lambda函数为参数,以闭包形式返回,返回值为最后一行的值或者指定的return的表达式。
- run函数的kotlin和Java转化
//kotlin
fun main(args: Array<String>) {
val user = User("Kotlin", 1, "1111111")
val result = user.run {
println("my name is $name, I am $age years old, my phone number is $phoneNum")
1000
}
println("result: $result")
}
//java
public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
User user = new User("Kotlin", 1, "1111111");
String var5 = "my name is " + user.getName() + ", I am " + user.getAge() + " years old, my phone number is " + user.getPhoneNum();
System.out.println(var5);
int result = 1000;
String var3 = "result: " + result;
System.out.println(var3);
}
- run函数的适用场景
适用于let,with函数任何场景。因为run函数是let,with两个函数结合体,准确来说它弥补了let函数在函数体内必须使用it参数替代对象,在run函数中可以像with函数一样可以省略,直接访问实例的公有属性和方法,另一方面它弥补了with函数传入对象判空问题,在run函数中可以像let函数一样做判空处理
- run函数使用前后的对比
还是借助上个例子kotlin代码
```
override fun onBindViewHolder(holder: ViewHolder, position: Int){
val item = getItem(position)?: return
with(item){
holder.tvNewsTitle.text = StringUtils.trimToEmpty(titleEn)
holder.tvNewsSummary.text = StringUtils.trimToEmpty(summary)
holder.tvExtraInf = "难度:$gradeInfo | 单词数:$length | 读后感: $numReviews"
...
}
}
```
使用run函数后的优化
```
override fun onBindViewHolder(holder: ViewHolder, position: Int){
getItem(position)?.run{
holder.tvNewsTitle.text = StringUtils.trimToEmpty(titleEn)
holder.tvNewsSummary.text = StringUtils.trimToEmpty(summary)
holder.tvExtraInf = "难度:$gradeInfo | 单词数:$length | 读后感: $numReviews"
...
}
}
```
apply — 内联扩展函数
- apply函数使用的一般结构
object.apply{
//todo
}
- apply函数的inline+lambda结构
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
- apply函数的inline结构分析
从结构上来看apply函数和run函数很像,唯一不同点就是它们各自返回的值不一样,run函数是以闭包形式返回最后一行代码的值,而apply函数的返回的是传入对象的本身。
- apply函数的kotlin和Java转化
//kotlin
fun main(args: Array<String>) {
val user = User("Kotlin", 1, "1111111")
val result = user.apply {
println("my name is $name, I am $age years old, my phone number is $phoneNum")
1000
}
println("result: $result")
}
//java
public final class ApplyFunctionKt {
public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
User user = new User("Kotlin", 1, "1111111");
String var5 = "my name is " + user.getName() + ", I am " + user.getAge() + " years old, my phone number is " + user.getPhoneNum();
System.out.println(var5);
String var3 = "result: " + user;
System.out.println(var3);
}
}
- apply函数的适用场景
整体作用功能和run函数很像,唯一不同点就是它返回的值是对象本身,而run函数是一个闭包形式返回,返回的是最后一行的值。正是基于这一点差异它的适用场景稍微与run函数有点不一样。apply一般用于一个对象实例初始化的时候,需要对对象中的属性进行赋值。或者动态inflate出一个XML的View的时候需要给View绑定数据也会用到,这种情景非常常见。特别是在我们开发中会有一些数据model向View model转化实例化的过程中需要用到。
- apply函数使用前后的对比
没有使用apply函数的代码是这样的,看起来不够优雅
```
mSheetDialogView = View.inflate(activity, R.layout.biz_exam_plan_layout_sheet_inner, null)
mSheetDialogView.course_comment_tv_label.paint.isFakeBoldText = true
mSheetDialogView.course_comment_tv_score.paint.isFakeBoldText = true
mSheetDialogView.course_comment_tv_cancel.paint.isFakeBoldText = true
mSheetDialogView.course_comment_tv_confirm.paint.isFakeBoldText = true
mSheetDialogView.course_comment_seek_bar.max = 10
mSheetDialogView.course_comment_seek_bar.progress = 0
```
使用apply函数后的代码是这样的
```
mSheetDialogView = View.inflate(activity, R.layout.biz_exam_plan_layout_sheet_inner, null).apply{
course_comment_tv_label.paint.isFakeBoldText = true
course_comment_tv_score.paint.isFakeBoldText = true
course_comment_tv_cancel.paint.isFakeBoldText = true
course_comment_tv_confirm.paint.isFakeBoldText = true
course_comment_seek_bar.max = 10
course_comment_seek_bar.progress = 0
}
```
多层级判空问题
```
if (mSectionMetaData == null || mSectionMetaData.questionnaire == null || mSectionMetaData.section == null) {
return;
}
if (mSectionMetaData.questionnaire.userProject != null) {
renderAnalysis();
return;
}
if (mSectionMetaData.section != null && !mSectionMetaData.section.sectionArticles.isEmpty()) {
fetchQuestionData();
return;
}
```
kotlin的apply函数优化
```
mSectionMetaData?.apply{
//mSectionMetaData不为空的时候操作mSectionMetaData
}?.questionnaire?.apply{
//questionnaire不为空的时候操作questionnaire
}?.section?.apply{
//section不为空的时候操作section
}?.sectionArticle?.apply{
//sectionArticle不为空的时候操作sectionArticle
}
```
also — 内联扩展函数
- also函数使用的一般结构
object.also{
//todo
}
- also函数的inline+lambda结构
@kotlin.internal.InlineOnly
@SinceKotlin(“1.1”)
public inline fun T.also(block: (T) -> Unit): T { block(this); return this }
```
- also函数的inline结构分析
also函数的结构实际上和let很像唯一的区别就是返回值的不一样,let是以闭包的形式返回,返回函数体内最后一行的值,如果最后一行为空就返回一个Unit类型的默认值。而also函数返回的则是传入对象的本身
- also函数编译后的class文件
//kotlin
fun main(args: Array<String>) {
val result = "testLet".also {
println(it.length)
1000
}
println(result)
}
//java
public final class AlsoFunctionKt {
public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
String var2 = "testLet";
int var4 = var2.length();
System.out.println(var4);
System.out.println(var2);
}
}
- also函数的适用场景
适用于let函数的任何场景,also函数和let很像,只是唯一的不同点就是let函数最后的返回值是最后一行的返回值而also函数的返回值是返回当前的这个对象。一般可用于多个扩展函数链式调用
- also函数使用前后的对比
和let函数类似
let,with,run,apply,also函数区别
函数名 | 定义inline的结构 | 函数体内使用的对象 | 返回值 | 是否是扩展函数 | 适用的场景 |
---|---|---|---|---|---|
let | fun <T, R> T.let(block: (T) -> R): R = block(this) | it指代当前对象 | 闭包形式返回 | 是 | 适用于处理不为null的操作场景 |
with | fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block() | this指代当前对象或者省略 | 闭包形式返回 | 否 | 适用于调用同一个类的多个方法时,可以省去类名重复,直接调用类的方法即可,经常用于Android中RecyclerView中onBinderViewHolder中,数据model的属性映射到UI上 |
run | fun <T, R> T.run(block: T.() -> R): R = block() | this指代当前对象或者省略 | 闭包形式返回 | 是 | 适用于let,with函数任何场景。 |
apply | fun T.apply(block: T.() -> Unit): T { block(); return this } | this指代当前对象或者省略 | 返回this | 是 | 1、适用于run函数的任何场景,一般用于初始化一个对象实例的时候,操作对象属性,并最终返回这个对象。 2、动态inflate出一个XML的View的时候需要给View绑定数据也会用到. 3、一般可用于多个扩展函数链式调用 4、数据model多层级包裹判空处理的问题 |
also | fun T.also(block: (T) -> Unit): T { block(this); return this } | it指代当前对象 | 返回this | 是 | 适用于let函数的任何场景,一般可用于多个扩展函数链式调用 |
use函数的原型
/**
* Executes the given [block] function on this resource and then closes it down correctly whether an exception
* is thrown or not.
*
* @param block a function to process this [Closeable] resource.
* @return the result of [block] function invoked on this resource.
*/
@InlineOnly
@RequireKotlin("1.2", versionKind = RequireKotlinVersionKind.COMPILER_VERSION, message = "Requires newer compiler version to be inlined correctly.")
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var exception: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
exception = e
throw e
} finally {
when {
apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception)
this == null -> {}
exception == null -> close()
else ->
try {
close()
} catch (closeException: Throwable) {
// cause.addSuppressed(closeException) // ignored here
}
}
}
}
- 可以看出,use函数内部实现也是通过try-catch-finally块捕捉的方式,所以不用担心会有异常抛出导致程序退出
- close操作在finally里面执行,所以无论是正常结束还是出现异常,都能正确关闭调用者
Java—— 实现读取一个文件内每一行的功能
//Java 实现
FileInputStream fis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream("/home/test.txt");
dis = new DataInputStream(new BufferedInputStream(fis));
String lines = "";
while((lines = dis.readLine()) != null){
System.out.println(lines);
}
} catch (IOException e){
e.printStackTrace();
} finally {
try {
if(dis != null)
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Kotlin实现
File("/home/test.txt").readLines()
.forEach { println(it) }
- 对Kotlin就是可以两行实现。
- 仔细翻阅readLines这个扩展函数的实现你会发现,它也是间接调用了use,这样就省去了捕捉异常和关闭的烦恼
- 同样的,经过包装以后你只需要关注读出来的数据本身而不需要care各种异常情况
File的一些其它有用的扩展函数
/**
* 将文件里的所有数据以字节数组的形式读出
* Tip:显然这不适用于大文件,文件过大,会导致创建一个超大数组
*/
public fun File.readBytes(): ByteArray
/**
* 与上一个函数类似,不过这个是写(如果文件存在,则覆盖)
*/
public fun File.writeBytes(array: ByteArray): Unit
/**
* 将array数组中的数据添加到文件里(如果文件存在则在文件尾部添加)
*/
public fun File.appendBytes(array: ByteArray): Unit
/**
* 将文件以指定buffer大小,分块读出(适用于大文件,也是最常用的方法)
*/
public fun File.forEachBlock(action: (buffer: ByteArray, bytesRead: Int) -> Unit): Unit
/**
* Gets the entire content of this file as a String using UTF-8 or specified [charset].
*
* This method is not recommended on huge files. It has an internal limitation of 2 GB file size.
*
* @param charset character set to use.
* @return the entire content of this file as a String.
*/
public fun File.readText(charset: Charset = Charsets.UTF_8): String
/**
* Sets the content of this file as [text] encoded using UTF-8 or specified [charset].
* If this file exists, it becomes overwritten.
*
* @param text text to write into file.
* @param charset character set to use.
*/
public fun File.writeText(text: String, charset: Charset = Charsets.UTF_8): Unit
/**
* Appends [text] to the content of this file using UTF-8 or the specified [charset].
*
* @param text text to append to file.
* @param charset character set to use.
*/
public fun File.appendText(text: String, charset: Charset = Charsets.UTF_8): Unit
/**
* Reads this file line by line using the specified [charset] and calls [action] for each line.
* Default charset is UTF-8.
*
* You may use this function on huge files.
*
* @param charset character set to use.
* @param action function to process file lines.
*/
public fun File.forEachLine(charset: Charset = Charsets.UTF_8, action: (line: String) -> Unit): Unit
/**
* Reads the file content as a list of lines.
*
* Do not use this function for huge files.
*
* @param charset character set to use. By default uses UTF-8 charset.
* @return list of file lines.
*/
public fun File.readLines(charset: Charset = Charsets.UTF_8): List<String>
/**
* Calls the [block] callback giving it a sequence of all the lines in this file and closes the reader once
* the processing is complete.
* @param charset character set to use. By default uses UTF-8 charset.
* @return the value returned by [block].
*/
@RequireKotlin("1.2", versionKind = RequireKotlinVersionKind.COMPILER_VERSION, message = "Requires newer compiler version to be inlined correctly.")
public inline fun <T> File.useLines(charset: Charset = Charsets.UTF_8, block: (Sequence<String>) -> T): T
- 上面的函数都是基于use实现的,可以放心使用,而不用担心异常的发生,并且会自动关闭IO流
函数类型,高阶函数,Lambda表达式三者之间的关系
- 将函数的
参数类型
和返回值类型
抽象出来后,就得到了函数类型
。(View) -> Unit
就代表了参数类型
是 View返回值类型
为 Unit 的函数类型。 - 如果一个函数的参数
或者
返回值的类型是函数类型,那这个函数就是高阶函数
。很明显,我们刚刚就写了一个高阶函数,只是它比较简单而已。 - Lambda 就是函数的一种
简写
一张图看懂:函数类型
,高阶函数
,Lambda表达式
三者之间的关系:
回过头再看官方文档提供的例子:
fun <T, R> Collection<T>.fold(
initial: R,
combine: (acc: R, nextElement: T) -> R
): R {
var accumulator: R = initial
for (element: T in this) {
accumulator = combine(accumulator, element)
}
return accumulator
}
看看这个函数类型:(acc: R, nextElement: T) -> R
,是不是瞬间就懂了呢?这个函数接收两个参数,第一个参数类型是R
,第二个参数是T
,函数的返回类型是R
。
带接收者(Receiver)的函数类型:A.(B,C) -> D
说实话,这个名字也对初学者不太友好:带接收者的函数类型
(Function Types With Receiver),这里面的每一个字(单词)我都认识,但单凭这么点信息,初学者真的很难理解它的本质。
还是绕不开一个问题:「为什么?」
为什么要引入:带接收者的函数类型?
我们在上一章节中提到过,用 apply 来简化逻辑,我们是这样写的:
修改前:
if (user != null) {
...
username.text = user.name
website.text = user.blog
image.setOnClickListener { gotoImagePreviewActivity(user) }
}
修改后:
user?.apply {
...
username.text = name
website.text = blog
image.setOnClickListener { gotoImagePreviewActivity(this) }
}
请问:这个 apply 方法应该怎么实现?
上面的写法其实是简化后的 Lambda 表达式,让我们来反推,看看它简化前是什么样的:
// apply 肯定是个函数,所以有 (),只是被省略了
user?.apply() {
...
}
// Lambda 肯定是在 () 里面
user?.apply({ ... })
// 由于 gotoImagePreviewActivity(this) 里的 this 代表了 user
// 所以 user 应该是 apply 函数的一个参数,而且参数名为:this
user?.apply({ this: User -> ... })
所以,现在问题非常明确了,apply 其实接收一个 Lambda 表达式:{ this: User -> ... }
。让我们尝试来实现这个 apply 方法:
fun User.apply(block: (self: User) -> Unit): User{
block(self)
return this
}
user?.apply { self: User ->
...
username.text = self.name
website.text = self.blog
image.setOnClickListener { gotoImagePreviewActivity(this) }
}
由于 Kotlin 里面的函数形参是不允许被命名为 this
的,因此我这里用的 self
,我们自己写出来的 apply 仍然还要通过 self.name
这样的方式来访问成员变量,但 Kotlin 的语言设计者能做到这样:
// 改为 this
// ↓
fun User.apply(block: (this: User) -> Unit): User{
// 这里还要传参数
// ↓
block(this)
return this
}
user?.apply { this: User ->
...
// this 可以省略
// ↓
username.text = this.name
website.text = blog
image.setOnClickListener { gotoImagePreviewActivity(this) }
}
从上面的例子能看到,我们反推的 apply 实现比较繁琐,需要我们自己调用:block(this)
,因此 Kotlin 引入了带接收者的函数类型
,可以简化 apply 的定义:
// 带接收者的函数类型
// ↓
fun User.apply(block: User.() -> Unit): User{
// 不用再传this
// ↓
block()
return this
}
user?.apply { this: User ->
...
username.text = this.name
website.text = this.blog
image.setOnClickListener { gotoImagePreviewActivity(this) }
}
现在,关键来了。上面的 apply 方法是不是看起来就像是在 User 里增加了一个成员方法 apply()?
class User() {
val name: String = ""
val blog: String = ""
fun apply() {
// 成员方法可以通过 this 访问成员变量
username.text = this.name
website.text = this.blog
image.setOnClickListener { gotoImagePreviewActivity(this) }
}
}
所以,从外表上看,带接收者的函数类型,就等价于成员方法。但从本质上讲,它仍是通过编译器注入 this 来实现的。
一张图总结: