当前位置:嗨网首页>书籍在线阅读

06-标准库

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

2.2.4 标准库

Kotlin 1.1版本添加了很多有用的标准库,为Kotlin开发带来了很多的便利。

1.字符串到数字的转换

String类中添加了一些新的扩展,比如使用它将String转换成数字而不会抛出异常,提供的方法有String.toIntOrNull():Int?、String.toDoubleOrNull(): Double?等。代码示例如下。

val port = System.getenv("PORT")?.toIntOrNull() ?: 80

除此之外,该标准库还提供了整数转换函数,如String.toIntOrNull()。

2.onEach()

onEach 是一个小而精的扩展函数,对于集合和序列很有用处,它允许对操作链中的每个元素执行一些特殊的操作,也可以使用forEach函数进一步返回可迭代实例。

inputDir.walk()
        .filter { it.isFile && it.name.endsWith(".txt") }
        .onEach { println("Moving $it to $outputDir") }
        .forEach { moveFile(it, File(outputDir, it.toRelativeString(inputDir))) 
}

3.groupingBy()

此API可以用于按照键对集合进行分组,同时折叠每个组。例如,下面的例子使用groupingBy()统计文字的使用频次。

fun main(args: Array<String>) {
    val words = "one two three four five six seven eight nine ten".split(' ')
    val frequencies = words.groupingBy { it.first() }.eachCount()
    println("Counting the letters: $frequencies.")
}

上面的代码输出结果如下。

[Counting the letters: {o=1, t=3, f=2, s=2, e=1, n=1}]

4.map.toMap()和map.toMutableMap()

这两个函数专门用来复制映射,代码示例如下。

class ImmutablePropertyBag(map: Map<String, Any>) { 
private val mapCopy = map.toMap() 
}

5.列表实例化函数

类似于Array构造函数,下面是创建 List 和 MutableList 的实例。

fun main(args: Array<String>) {
    val squares = List(10) { index -> index * index }
    val mutable = MutableList(10) { 0 }
    println("squares: $squares")  //输出结果:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    println("mutable: $mutable")  //输出结果:[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}

6.抽象集合

这些抽象类可以在实现Kotlin集合类时用作基类。在只读集合实现上主要有AbstractCollection、AbstractList、AbstractSet和AbstractMap;在可变集合实现上主要有AbstractMutableList、AbstractMutableSet、AbstractMutableMap和AbstractMutableCollection。

7.数组处理函数

现在,Kotlin标准库提供了一组用于逐个元素操作数组的函数,例如,比较(contentEquals和contentDeepEquals)、散列码计算以及数组转换为字符串操作。代码示例如下。

fun main(args: Array<String>) {
    val array = arrayOf("a", "b", "c")
    println(array.toString())  //输出结果:[Ljava.lang.String;@5305068a
    println(array.contentToString())  //格式化列表,输出结果:[a, b, c]
}