Skip to content

Commit

Permalink
modify: kotlin_function_three_common_methods
Browse files Browse the repository at this point in the history
  • Loading branch information
heliangwei committed Jul 8, 2016
1 parent 57b61bd commit 31635a2
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions source/_posts/kotlin_function_three_common_methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ val names = arrayOf("James", "Tom", "Jack", "Kobe");
val namesLength = names.map { it.length }
```

映射函数是将一个集合映射成另外一种集合,所以当你需要见一个HaspMap映射成一个List的时候,会非常方便。

```
val params = mapOf("limit" to "10", "offset" to "20", "order" to "asc")
val s = params.map { "${it.key}=${it.value}" }.joinToString("&")
// s = limit=10&offset=20&order=asc
```

`filter`相似,kotlin也提供的`mapIndexed`的类似方法方便使用,针对`Map`类型的集合也有`mapKeys``mapValues`的封装。

## Reduce
Expand All @@ -92,6 +100,8 @@ val texts = arrayOf("芦花丛中一扁舟", "俊杰俄从此地游", "义士若
val result = texts.map { it.substring(0,1) }.reduce { r, s -> "$r$s"}
```

最后得到的结果是`卢俊义反`

## 函数式编程

函数式编程的精髓在于函数本身。在函数式编程中函数是第一等公民,与其他数据类型一样,处于平等地位,可以赋值给其他变量,也可以作为参数,传入另一个函数,或者作为别的函数的返回值。
Expand Down

0 comments on commit 31635a2

Please sign in to comment.