9-1 Array
scala> val arr = Array(1,2)
arr: Array[Int] = Array(1, 2)
def map[B, That](f: Int => B)(implicit bf: scala.collection.generic.CanBuildFrom[Array[Int],B,That]): That scala> def add(a:Int)={| a * 2| } add: (a: Int)Int scala> arr.map(add) res17: Array[Int] = Array(2, 4)
scala> arr.foreachoverride def foreach[U](f: Int => U): Unit scala> arr.foreach(println) 1 2
scala> arr.filterdef filter(p: Int => Boolean): Array[Int] scala> val arr = Array(1 to 10:_*) arr: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)scala> arr.filter(_ % 2 == 0) res45: Array[Int] = Array(2, 4, 6, 8, 10)
a b
-------------
1 2
3 3
6 4
10 5
res:15
res:-13
a b
-------
4 5
3 9
2 12
1 14
res: 15
map
//說明def map[B, That](f: Int => B)(implicit bf: scala.collection.generic.CanBuildFrom[Array[Int],B,That]): That scala> def add(a:Int)={| a * 2| } add: (a: Int)Int scala> arr.map(add) res17: Array[Int] = Array(2, 4)
scala> arr.map(i => math.pow(i,i)) //傳遞匿名函數
res28: Array[Double] = Array(1.0, 4.0)
foreach:[trait] IndexedSeqOptimized
//說明scala> arr.foreachoverride def foreach[U](f: Int => U): Unit scala> arr.foreach(println) 1 2
filter
//說明scala> arr.filterdef filter(p: Int => Boolean): Array[Int] scala> val arr = Array(1 to 10:_*) arr: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)scala> arr.filter(_ % 2 == 0) res45: Array[Int] = Array(2, 4, 6, 8, 10)
reduce:+ 等同??reduceLeft
val res = arr.reduce((a,b) => a+b) 過程如下:a b
-------------
1 2
3 3
6 4
10 5
res:15
reduce:- 等同??reduceLeft
val res = arr.reduce((a,b) => a-b)res:-13
reduceRight:+
val res = arr.reduceRight((a,b) => a+b) 過程如下:a b
-------
4 5
3 9
2 12
1 14
res: 15
reduceRight:-
val res = arr.reduceRight(_-_) 過程如下: a b ------- 4 5 3 -1 2 4 1 -2 res: 3?
轉載于:https://www.cnblogs.com/lybpy/p/9739954.html
總結
- 上一篇: 关于Unity实现AR功能(四)设置相机
- 下一篇: ArrayList的实现原理