本文使用的方法都是来自Kotlin中源码标准库(Standard.kt)
为了有些朋友看不到,我下面贴心的把源码贴出来了
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("StandardKt")
package kotlin
import kotlin.contracts.*
/**
* An exception is thrown to indicate that a method body remains to be implemented.
*/
public class NotImplementedError(message: String = "An operation is not implemented.") : Error(message)
/**
* Always throws [NotImplementedError] stating that operation is not implemented.
*/
@kotlin.internal.InlineOnly
public inline fun TODO(): Nothing = throw NotImplementedError()
/**
* Always throws [NotImplementedError] stating that operation is not implemented.
*
* @param reason a string explaining why the implementation is missing.
*/
@kotlin.internal.InlineOnly
public inline fun TODO(reason: String): Nothing = throw NotImplementedError("An operation is not implemented: $reason")
/**
* Calls the specified function [block] and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#run).
*/
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
/**
* Calls the specified function [block] with `this` value as its receiver and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#run).
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
/**
* Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#with).
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
/**
* Calls the specified function [block] with `this` value as its receiver and returns `this` value.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#apply).
*/
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
/**
* Calls the specified function [block] with `this` value as its argument and returns `this` value.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#also).
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}
/**
* Calls the specified function [block] with `this` value as its argument and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#let).
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
/**
* Returns `this` value if it satisfies the given [predicate] or `null`, if it doesn't.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#takeif-and-takeunless).
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (predicate(this)) this else null
}
/**
* Returns `this` value if it _does not_ satisfy the given [predicate] or `null`, if it does.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#takeif-and-takeunless).
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (!predicate(this)) this else null
}
/**
* Executes the given function [action] specified number of [times].
*
* A zero-based index of current iteration is passed as a parameter to [action].
*
* @sample samples.misc.ControlFlow.repeat
*/
@kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
contract { callsInPlace(action) }
for (index in 0 until times) {
action(index)
}
}
别小看这50行代码,功能非常强大,如果使用的话,代码的优雅会上一个台阶。
下面我简单拿出来几个方法来比较一下
一、回调函数的Kotlin的lambda的简化
如果接口里面只有单个方法,可以使用lambda来简化
- Java
// Java
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//todo
}
});
- Kotlin不适用lambda
button.setOnClickListener(object: View.OnClickListener() {
override fun onClick(view: View) {
//todo
}
})
- Kotlin lambda的写法
button.setOnClickListener({
view: View ->
//todo
})
// 或者可以直接省略Data,借助kotlin的智能类型推导
button.setOnClickListener({
view ->
//todo
})
// 如果代码中没有使用view参数,可以把view去掉
button.setOnClickListener({
//todo
})
//如果最后一个参数是函数,可以把括号的视线提到圆括号外面
button.setOnClickListener() {
//todo
}
//如果这个函数只有一个参数,可以省略圆括号
button.setOnClickListener {
// todo
}
- Kotlin lambda优雅的写法
button.setOnClickListener {
// todo
}
二、内联扩展函数的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
}
print(result)
}
// java
public final class LetFunctionKt {
public static final void main(@NotNul 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_vide)
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()
3.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 namme is $name, I am $age years old, my phone number is $phoneNum")
}
println("result: $result")
}
// java
public static final void main(@Notnull String[] args) {
Intrinsics.checkParamterIsNotNull(args, "args");
User user = new User("Kotlin", 1, "1111111");
String vaar4 = "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));
SString gradeIngfo = "难度:" + item.gradeInfo;
String wordCount = "单词数:" + item.length;
String reviewNum = "读后感:" + item.numReviews;
String extraInfo = gradeInfo + " | " + wordCount + " | " + reviewNum;
holder.tcExtraInfo.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:$resule")
}
// java
public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIssNotNull(args, "args");
User user = new User("Kotlin", 1, "1111111");
String var5 = "my name is " + user.getName() + ", I amm " + user.getAge() + " years old, my phone number is " + user.getPhoneNum();
System.out.println(var5);
int result = 1000;
SString var3 = "result:" + result;
System.out.println(var3);
}
-
run函数的适用场景 适用于let,with函数任何场景。因为run函数是let,with两个函数结合体,准确来说它弥补了let函数的函数体内必须使用it参数替代对象,在run函数中可以像with函数一样可以省略,最直接访问实例的共有属性和方法,另一方面它弥补了with函数传入对象判空问题,在run函数中可以像let函数一样做判空处理。
-
run函数使用前后的对比
还是借助上个例子kotlin代码
override fun obBindViewHolder(holder: ViewHolder, position: Int) {
let 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.txExtraInf = "难度:$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, "111111");
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_example_plan_layout_sheet_inner, null)
mSheetDialogView.course_comment_tv_label.paint.isFakeBoldText = true
mSheetDialogView.course_comment_tv_sorce.paint.isFakeBoldText = true
mSheetDialogView.course_comment_tv_calcel.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 inlin 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) {
Intrinstics.checkParamterIsNotNull(args, "args");
String var2 = "testLet";
int var = var2.length();
System.out.println(var4);
System.out.println(var2);
}
}
- also函数的适用场景
适用于let函数的任何场景,also函数和let很像,只是唯一的不同点就是let函数最后的返回值是最后一行值而also函数的返回值是返回当前的这个对。一般可用于多个扩展函数链式调用
- also韩式使用前后的对比 和let函数类似。
七、let,with,run,apply,also函数区别 通过以上几种函数的介绍,可以很方便优化kotlin中代码编写,整体看起来几个函数的作用很相似,但是各自又存在着不同。使用的场景有相同的地方比如run函数就是let和with的结合体。下面一张表格可以清晰对比出他们的不同之处。
| 函数名 | 定义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函数的任何场景,一般可用于多个扩展函数链式调用 |