
上QQ阅读APP看书,第一时间看更新
3.2.3 简化Kotlin的Lambda表达式
Kotlin的Lambda表达式可以不断地被简化。以处理Android View的点击事件为例,使用Java的代码大致如下:

按照Java的风格来编写Kotlin的代码,使用Kotlin的对象表达式:

再对上述代码使用Lambda表达式:

如果参数为函数类型并且是最后一个参数,那么可以将参数移到函数的括号外面:

如果参数只有一个Lambda表达式,那么函数的小括号可以省略:

最后,在单击事件中,如果会使用到view,那么“v ->”可以省略,使用默认参数it进行替代:

小结一下简化Lambda表达式的规则:
· 在函数中,最后一个参数是函数类型,那么可以将Lambda移到函数的括号外面。
· 如果函数的参数只有一个Lambda,那么函数的小括号可以省略。
· 在Lambda表达式中只有一个参数,可以使用默认参数it进行替代。
· 对于有多个参数的Lambda表达式,如果某个参数未使用,可以用下画线“_”取代其名称。
· 入参、返回值与形参一致的函数,可以用方法引用的方式作为实参传入。