Kotlin 学习笔记,2020-06-22

上期笔记


https://kotlinlang.org/docs/reference/constructing-collections.html#constructing-collections

毫无意外的一节。不过有两点值得一说:

第一是之前看到的构造 map 时候的 a to b 的语法,原来是中缀函数:

val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)

嗯,这倒确实是一个合理的场景,可以支持一下引入中缀函数的价值。

第二是 associateWith 这个东西感觉确实方便:

val numbers = listOf("one", "two", "three", "four")
println(numbers.associateWith { it.length })

https://kotlinlang.org/docs/reference/iterators.html#iterators

毫无意外的一节。


https://kotlinlang.org/docs/reference/ranges.html#ranges-and-progressions

又是毫无意外的一节。讲真我不是很明白为啥这么多语言都在 rangeprogression 上费老大功夫。传统 C 语言 for 循环的处理方式不香么?


https://kotlinlang.org/docs/reference/sequences.html

一言以蔽之,惰性求值的列表。


https://kotlinlang.org/docs/reference/collection-operations.html#collection-operations-overview
https://kotlinlang.org/docs/reference/collection-transformations.html#collection-transformations
https://kotlinlang.org/docs/reference/collection-filtering.html#filtering
https://kotlinlang.org/docs/reference/collection-plus-minus.html#plus-and-minus-operators
https://kotlinlang.org/docs/reference/collection-grouping.html#grouping
https://kotlinlang.org/docs/reference/collection-parts.html#retrieving-collection-parts
https://kotlinlang.org/docs/reference/collection-elements.html#retrieving-single-elements
https://kotlinlang.org/docs/reference/collection-ordering.html#collection-ordering
https://kotlinlang.org/docs/reference/collection-aggregate.html#collection-aggregate-operations
https://kotlinlang.org/docs/reference/collection-write.html#collection-write-operations
https://kotlinlang.org/docs/reference/list-operations.html#list-specific-operations
https://kotlinlang.org/docs/reference/set-operations.html#set-specific-operations
https://kotlinlang.org/docs/reference/map-operations.html#map-specific-operations

基本上是函数式语言的滥觞 + Java collections 熟悉的味道。少数值得一提的:

val numbers = listOf(null, 1, "two", 3.0, "four")
// filterIsInstance 可以从 List<Any> 里面过滤出 List<String> 来
val filtered : List<String> = numbers.filterIsInstance<String>()
filtered.forEach {
    println(it.toUpperCase())
}
// binarySearch 返回 (-insertionPoint - 1) ,如果给定元素找不到的话。
// 不太理解这个设计。
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sort()
println(numbers)
println(numbers.binarySearch("two"))  // 3
println(numbers.binarySearch("z")) // -5
println(numbers.binarySearch("two", 0, 2))  // -3
// 原生支持的集合操作,感觉还挺不错的。
val numbers = setOf("one", "two", "three")

println(numbers union setOf("four", "five"))
println(setOf("four", "five") union numbers)

println(numbers intersect setOf("two", "one"))
println(numbers subtract setOf("three", "four"))
println(numbers subtract setOf("four", "three")) // same output
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。