用于按照键对集合进行分组,并同时折叠每个组。通常用于统计字符出现的次数
方法签名:
/**
* Creates a [Grouping] source from a collection to be used later with one of group-and-fold operations
* using the specified [keySelector] function to extract a key from each element.
*
* @sample samples.collections.Collections.Transformations.groupingByEachCount
*/
@SinceKotlin("1.1")
public inline fun Iterable.groupingBy(crossinline keySelector: (T) -> K): Grouping {}
示例:
val list = listOf("bda", "cdg", "ae", "crg3")
list.groupingBy { it.first() }.eachCount().forEach(::println)
结果:
b=1
c=2
a=1
用于对集合进行分组。通常用于分组显示数据
方法签名:
/**
* Groups elements of the original collection by the key returned by the given [keySelector] function
* applied to each element and returns a map where each group key is associated with a list of corresponding elements.
*
* The returned map preserves the entry iteration order of the keys produced from the original collection.
*
* @sample samples.collections.Collections.Transformations.groupBy
*/
public inline fun Iterable.groupBy(keySelector: (T) -> K): Map> {}
示例:
val list = listOf("bda", "cdg", "ae", "crg3")
list.groupBy { it.first() }.forEach(::println)
结果:
b=[bda]
c=[cdg, crg3]
a=[ae]
T的扩展方法,执行一个代码块,返回R。通常用于处理可null对象
方法签名:
/**
* Calls the specified function [block] with `this` value as its argument and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun T.let(block: (T) -> R): R{}
示例:
val data = 1
data?.let {
println("data is not null")
}
结果:
data is not null
接收一个对象和一个函数,这个函数会作为这个对象的扩展函数执行。这表示我们根据推断可以在函数内使用 this 。
方法签名:
/**
* Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun with(receiver: T, block: T.() -> R): R {}
示例:
with(TextView(context)) {
text = "Hello"
hint = "Hint"
setTextColor(android.R.color.white)
}
T的扩展方法,执行T的另一个方法代码块,并返回T。通常用来替换创建builder的使用方式。等价于with()函数返回this
方法签名:
/**
* Calls the specified function [block] with `this` value as its receiver and returns `this` value.
*/
@kotlin.internal.InlineOnly
public inline fun T.apply(block: T.() -> Unit): T {}
示例:
val textView = TextView(context).apply {
text = "Hello"
hint = "Hint"
setTextColor(android.R.color.white)
}
Closeable实现类的扩展方法,用来执行一段代码块,并且不管是否抛出异常,都会正确地关闭它。不再需要自己去手动释放资源。
方法签名:
/**
* 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
public inline fun T.use(block: (T) -> R): R {}
示例:
FileInputStream("build.gradle").buffered().reader().use { reader -> println(reader.readText()) }