一、定義變量java
var 可變es6
val 不可變,至關於Java中的final編程
Unit至關於Java中的void,以()表示數組
scala> val a = println("ddd")
ddd
a: Unit = ()app
2,聲明數組ide
scala> val arr = Array(1,2,3,4,5)
arr: Array[Int] = Array(1, 2, 3, 4, 5)函數式編程
3,for循環函數
scala> for(ele <- arr){
println(ele)
}
1
2
3
4
5測試
scala> for(ele <- 0 to 4) {
println(arr(ele))
}
1
2
3
4
5es5
scala> for(ele <- 0 until 5) {
println(arr(ele))
}
1
2
3
4
5
帶條件的循環
scala> for(ele <- arr if ele % 2==0) println(ele)
2
4
雙層for循環
scala> for(i <- 1 to 3;j <- 1 to 3 if i !=j) println((10 * i + j))
12
13
21
23
31
32
把循環結果賦給一個新的數組
scala> val r1 = for(a <- arr if a % 2 == 0) yield a
r1: Array[Int] = Array(2, 4)
4,定義方法
scala> def add(a: Int,b: Int) = a + b
add: (a: Int, b: Int)Int
scala> add(2,5)
res7: Int = 7
無參無返回
scala> def say = println("hello")
say: Unit
scala> say
hello
方法轉函數
scala> add _
res9: (Int, Int) => Int = <function2>
5,定義函數
scala> val fx = (a: Int,b: Int) => a + b
fx: (Int, Int) => Int = <function2>
scala> fx(3,6)
res10: Int = 9
scala> val fn:(Int,Int) => Int = (x,y) => x + y
fn: (Int, Int) => Int = <function2>
scala> fn(6,2)
res11: Int = 8
scala> val f1 = (name: String) => println(name)
f1: String => Unit = <function1>
scala> f1("ggg")
ggg
scala> val f2:(String) => Unit = name => println(name)
f2: String => Unit = <function1>
scala> f2("hhh")
hhh
6,傳值調用(方法)和傳名調用(函數)
傳值是把100-5=95的值給循環了3次,輸出3個95,傳名是把countMoney方法隱式轉換成函數,把函數總體傳入循環,循環4次,money每次都會扣減5
object Money { var money = 100 def payMoney = { money -= 5 } def countMoney = { payMoney money } def printByValue(x: Int) = { for (a <- 0 until 3) println(s"測試:${x}元") } def printByName(x: => Int) = { for (a <- 0 to 3) println(s"測試:${x}元") } def main(args: Array[String]): Unit = { printByValue(countMoney) printByName(countMoney) } }
輸出結果
測試:95元
測試:95元
測試:95元
測試:90元
測試:85元
測試:80元
測試:75元
object Calculate { def add(a: Int,b: Int) = { a + b } def add2(f:(Int,Int) => Int,a: Int,b: Int) = { f(a,b) } def add3(f:Int => Int,b: Int) = { f(b) + b } val fx = (a: Int,b: Int) => a + b val f = (a: Int) => a * 10 def main(args: Array[String]): Unit = { println(add(6,1)) println(add2(fx,13,5)) println(add3(f,6)) } }
輸出結果
7
18
66
7,可變參數以及參數的默認值
object ManyParams { def add(ints: Int*) = { var sum = 0 for (v <- ints) { sum += v } sum } def dee(a: Int = 6,b: Int = 4) = { a + b } def main(args: Array[String]): Unit = { val i = add(3,5) println(i) println(dee()) println(dee(b=1,a=6)) } }
輸出結果
8
10
7
8,高階函數
首先判斷調用的layout方法是否知足apply的第一個函數參數,很明顯,layout有一個Int的參數,返回的是字符串,徹底符合f:Int => String,而後根據f(v),把v做用在f函數中.
object HightFunc extends App{ def apply(f:Int => String,v:Int) = f(v) def layout(x:Int) = "[" + x.toString + "]" println(apply(layout,10)) }
輸出結果
[10]
9,部分參數應用函數
scala> def m(a: Int,b: Int) = a + b
m: (a: Int, b: Int)Int
scala> val partM = m(1,_:Int)
partM: Int => Int = <function1>
scala> partM(5)
res14: Int = 6
scala> val partM2 = (x: Int) => m(1,x)
partM2: Int => Int = <function1>
scala> partM2(6)
res15: Int = 7
import java.util.Date object PartParmFunc extends App{ def log(date: Date,message: String) = { println(s"$date,$message") } val date = new Date() val logBoundDate = log(date, _:String) logBoundDate("gogogo") }
輸出結果
Fri Sep 21 15:40:15 CST 2018,gogogo
10,柯里化
scala> def add(a: Int)(b: Int) = a + b
add: (a: Int)(b: Int)Int
scala> add(4)(8)
res16: Int = 12
高階函數演變
scala> def add(a: Int) = (b:Int) => a + b
add: (a: Int)Int => Int
scala> val x = add(5)
x: Int => Int = <function1>
scala> x(8)
res17: Int = 13
11,偏函數
object ScalaPartialFunction { def func(str: String): Int = { if (str.equals("a")) 97 else 0 } /** * 偏函數:PartialFunction[參數類型,返回值類型] * @return */ def func1:PartialFunction[String,Int] = { case "a" => 97 case _ => 0 } def f1:PartialFunction[Any,Int] = { case i:Int => i * 10 } def main(args: Array[String]): Unit = { println(func("a")) println(func1("a")) val arr = Array[Any](1,2,4,"你大爺的") val arr1 = Array(1,3,6,8) val collect = arr.collect(f1) val collect1 = arr1.map((x: Int) => x * 10) val collect2 = arr1.map(x => x * 10) val collect3 = arr1.map(_ * 10) val collect4 = arr1.map {case x: Int => x * 10} println(collect.toBuffer) println(collect1.toBuffer) println(collect2.toBuffer) println(collect3.toBuffer) println(collect4.toBuffer) } }
輸出結果
97
97
ArrayBuffer(10, 20, 40)
ArrayBuffer(10, 30, 60, 80)
ArrayBuffer(10, 30, 60, 80)
ArrayBuffer(10, 30, 60, 80)
ArrayBuffer(10, 30, 60, 80)
12,數組使用
new關鍵字初始數組
scala> val arr = new Array[Int](3)
arr: Array[Int] = Array(0, 0, 0)
scala> arr(0) = 100
scala> arr
res1: Array[Int] = Array(100, 0, 0)
長度不可變,內容可變
map映射
val arr = Array(1,3,5,7,8) //map映射 val fx = (x: Int) => x * 10 //ar1通過map映射操做後會返回一個新的數組 val ar1 = arr.map(fx)
flatten,flatMap扁平化
scala> val arr = Array("hello tom","hello jenie")
arr: Array[String] = Array(hello tom, hello jenie)
scala> arr.length
res4: Int = 2
scala> arr.map(_.split(" "))
res5: Array[Array[String]] = Array(Array(hello, tom), Array(hello, jenie))
scala> arr.map(_.split(" ")).flatten
res6: Array[String] = Array(hello, tom, hello, jenie)
scala> arr.flatMap(_.split(" "))
res7: Array[String] = Array(hello, tom, hello, jenie)
foreach遍歷
scala> arr.flatMap(_.split(" ")).foreach(println)
hello
tom
hello
jenie
scala> arr.flatMap(_.split(" ")).foreach(x => println(x))
hello
tom
hello
jenie
groupBy分組(Map)
scala> arr.flatMap(_.split(" ")).groupBy(x => x)
res10: scala.collection.immutable.Map[String,Array[String]] = Map(jenie -> Array(jenie), tom -> Array(tom), hello -> Array(hello, hello))
Map取值(List)
scala> arr.flatMap(_.split(" ")).groupBy(x => x).map(x => x._2)
res11: scala.collection.immutable.Iterable[Array[String]] = List(Array(jenie), Array(tom), Array(hello, hello))
取每一個Map值的長度
scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length)
res12: scala.collection.immutable.Map[String,Int] = Map(jenie -> 1, tom -> 1, hello -> 2)
轉成list(map不能排序)
scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length).toList
res13: List[(String, Int)] = List((jenie,1), (tom,1), (hello,2))
list排序(升序)
scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length).toList.sortBy(x => x._2)
res14: List[(String, Int)] = List((jenie,1), (tom,1), (hello,2))
list排序(降序)
scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length).toList.sortBy(x => - x._2)
res15: List[(String, Int)] = List((hello,2), (jenie,1), (tom,1))
13,集合使用
長度可變數組(ArrayBuffer)
scala> import scala.collection.mutable._
import scala.collection.mutable._
scala> val ab = ArrayBuffer(1,2,3)
ab: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)
scala> ab += (4,5,6)
res17: ab.type = ArrayBuffer(1, 2, 3, 4, 5, 6)
scala> ab
res18: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5, 6)
/** * Array: * 內容均可變 * 長度可變數組(ArrayBuffer)和長度不可變數組Array * * 在Scala中,集合分爲可變集合(mutable)和不可變集合(immutable) * 可變集合指的是:長度可變,內容可變 * 不可變集合:長度不可變,內容也不可變 */
不可變List
scala> val list = List(1,2,4)
list: List[Int] = List(1, 2, 4)
scala> list += (5,7)
<console>:13: error: value += is not a member of List[Int]
list += (5,7)
^
scala> list(0) = 100
<console>:13: error: value update is not a member of List[Int]
list(0) = 100
可變List(ListBuffer)
scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer
scala> val lb = ListBuffer(1,2,3,4)
lb: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4)
scala> lb += (8,9)
res2: lb.type = ListBuffer(1, 2, 3, 4, 8, 9)
scala> lb
res3: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4, 8, 9)
scala> lb(0) = 100
scala> lb
res5: scala.collection.mutable.ListBuffer[Int] = ListBuffer(100, 2, 3, 4, 8, 9)
不可變Map
scala> val mp = Map("xx" -> 1)
mp: scala.collection.immutable.Map[String,Int] = Map(xx -> 1)
scala> mp
res1: scala.collection.immutable.Map[String,Int] = Map(xx -> 1)
可變Map(HashMap)
scala> import scala.collection.mutable.HashMap
import scala.collection.mutable.HashMap
scala> val hmp = HashMap("x" -> 1)
hmp: scala.collection.mutable.HashMap[String,Int] = Map(x -> 1)
scala> hmp
res0: scala.collection.mutable.HashMap[String,Int] = Map(x -> 1)
scala> hmp += "b" -> 0
res2: hmp.type = Map(b -> 0, x -> 1)
scala> hmp
res3: scala.collection.mutable.HashMap[String,Int] = Map(b -> 0, x -> 1)
List方法
scala> Nil
res5: scala.collection.immutable.Nil.type = List()
scala> val list = List(9,10,4,2,7,1)
list: List[Int] = List(9, 10, 4, 2, 7, 1)
scala> list.head
res6: Int = 9
scala> list.tail
res7: List[Int] = List(10, 4, 2, 7, 1)
右結合::生成爲新的List,全部結合前的不可變List不變
scala> 100 :: Nil
res8: List[Int] = List(100)
scala> val l = Nil
l: scala.collection.immutable.Nil.type = List()
scala> 9 :: l
res9: List[Int] = List(9)
scala> l
res10: scala.collection.immutable.Nil.type = List()
scala> 1::2::3::Nil
res11: List[Int] = List(1, 2, 3)
scala> Nil.::(3)
res0: List[Int] = List(3)
拼接生成新List
scala> val list = List(3,6,8)
list: List[Int] = List(3, 6, 8)
scala> list
res2: List[Int] = List(3, 6, 8)
scala> list ++ List(7,0,1)
res3: List[Int] = List(3, 6, 8, 7, 0, 1)
scala> list
res4: List[Int] = List(3, 6, 8) //原list不變
頭部合併(++:,+:)
scala> list. ++:(List(9))
res5: List[Int] = List(9, 3, 6, 8)
scala> list.+:(9527)
res6: List[Int] = List(9527, 3, 6, 8)
尾部合併(:+)
scala> list :+ (1)
res8: List[Int] = List(3, 6, 8, 1)
scala> list
res9: List[Int] = List(3, 6, 8)
拼接2個List(:::)
scala> list ::: List(1,5,7)
res10: List[Int] = List(3, 6, 8, 1, 5, 7)
統計條件數(count)
scala> list.count(x => x>2)
res1: Int = 3
過濾(filter)
scala> list.filter(x => x>3)
res2: List[Int] = List(6, 8)
排序(sorted,sortBy,sortWith)
scala> list.sorted
res3: List[Int] = List(3, 6, 8)
scala> list.sortBy(x => x)
res4: List[Int] = List(3, 6, 8)
scala> list.sortBy(x => - x)
res5: List[Int] = List(8, 6, 3)
scala> val wds = List(("a",1),("c",4),("t",2))
wds: List[(String, Int)] = List((a,1), (c,4), (t,2))
scala> wds.sortBy(x => x._2)
res6: List[(String, Int)] = List((a,1), (t,2), (c,4))
scala> wds.sortBy(x => - x._2)
res7: List[(String, Int)] = List((c,4), (t,2), (a,1))
scala> wds.sortWith((x, y) => x._2 > y._2)
res8: List[(String, Int)] = List((c,4), (t,2), (a,1))
分組(grouped)
scala> list.grouped(2).toList
res9: List[List[Int]] = List(List(3, 6), List(8))
scala> list.grouped(1).toList
res10: List[List[Int]] = List(List(3), List(6), List(8))
摺疊(fold,foldLeft,foldRight)
scala> list.fold(0)((x, y) => x + y)
res11: Int = 17
scala> list.fold(0)(_ + _)
res13: Int = 17
scala> list.foldLeft(0)(_ - _)
res14: Int = -17
scala> list.foldRight(0)(_ - _)
res15: Int = 5
反轉(reverse)
scala> list.reverse
res17: List[Int] = List(8, 6, 3)
聚合(reduce,aggregate)
scala> list.reduce((x, y) => x + y)
res18: Int = 17
scala> list.aggregate(0)(_ + _,_ + _)
res1: Int = 17
合併(union)
scala> val list2 = List(7,3,1)
list2: List[Int] = List(7, 3, 1)
scala> list.union(list2)
res2: List[Int] = List(3, 6, 8, 7, 3, 1)
交集(intersect)
scala> list.intersect(list2)
res3: List[Int] = List(3)
區別(diff)
scala> list.diff(list2)
res4: List[Int] = List(6, 8)
組合成元組(zip)
scala> list.zip(list2)
res5: List[(Int, Int)] = List((3,7), (6,3), (8,1))
格式化字符串(mkString)
scala> list.mkString("|")
res6: String = 3|6|8
scala> list.mkString("\t")
res7: String = 3 6 8
截取(slice)
scala> list.slice(1,3)
res8: List[Int] = List(6, 8)
scala> list.slice(1,list.length)
res10: List[Int] = List(6, 8)
求和(sum)
scala> list.sum
res11: Int = 17
Set方法
不可變Set
scala> val set = Set(1,5,5,8)
set: scala.collection.immutable.Set[Int] = Set(1, 5, 8)
可變Set(HashSet)
scala> import collection.mutable.HashSet
import collection.mutable.HashSet
scala> val hset = HashSet(1,4,7)
hset: scala.collection.mutable.HashSet[Int] = Set(1, 7, 4)
scala> hset.add(5)
res12: Boolean = true
scala> hset
res13: scala.collection.mutable.HashSet[Int] = Set(1, 5, 7, 4)
scala> hset.remove(1)
res14: Boolean = true
scala> hset
res15: scala.collection.mutable.HashSet[Int] = Set(5, 7, 4)
scala> hset.-=(5)
res9: hset.type = Set(7, 4)
scala> hset ++ Set(0,8)
res10: scala.collection.mutable.HashSet[Int] = Set(0, 7, 4, 8)
scala> hset
res11: scala.collection.mutable.HashSet[Int] = Set(7, 4) 此時原來的hset是無變化的
scala> hset ++= Set(0,8)
res12: hset.type = Set(0, 7, 4, 8)
scala> hset
res13: scala.collection.mutable.HashSet[Int] = Set(0, 7, 4, 8) 此時原來的hset是有變化的
不可變Map
scala> val mp = Map[String, Int]("a" -> 1)
mp: scala.collection.immutable.Map[String,Int] = Map(a -> 1)
可變Map
scala> import collection.mutable.HashMap
import collection.mutable.HashMap
scala> val mmp = HashMap[String, Int]()
mmp: scala.collection.mutable.HashMap[String,Int] = Map()
scala> mmp.put("bb",8)
res0: Option[Int] = None
scala> mmp
res1: scala.collection.mutable.HashMap[String,Int] = Map(bb -> 8)
scala> mmp += "name" -> 100
res2: mmp.type = Map(bb -> 8, name -> 100)
添加元組
scala> mmp += (("xx",98))
res3: mmp.type = Map(bb -> 8, name -> 100, xx -> 98)
刪除Key
scala> mmp.remove("xx")
res4: Option[Int] = Some(98)
scala> mmp
res5: scala.collection.mutable.HashMap[String,Int] = Map(bb -> 8, name -> 100)
scala> mmp.-=("name")
res6: mmp.type = Map(bb -> 8)
經過Key獲取value
scala> mmp.get("bb")
res8: Option[Int] = Some(8)
scala> mmp.get("bb").get
res9: Int = 8
若是沒有Key,get就獲取不到值
scala> mmp.get("aa")
res10: Option[Int] = None
scala> mmp.get("aa").get
java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:347)
at scala.None$.get(Option.scala:345)
... 32 elided
經過getOrElse能夠在沒有Key的狀況下,獲取一個默認值,map自己不變;若是Key存在,則直接返回value.
scala> mmp.getOrElse("aa",0)
res12: Int = 0
scala> mmp
res13: scala.collection.mutable.HashMap[String,Int] = Map(bb -> 8)
scala> mmp.getOrElse("bb",0)
res14: Int = 8
其中Some是一個樣例類
package scala @scala.SerialVersionUID(value = 1234815782226070388) final case class Some[+A](val x : A) extends scala.Option[A] with scala.Product with scala.Serializable { def isEmpty : scala.Boolean = { /* compiled code */ } //這裏是false def get : A = { /* compiled code */ } //這裏就是x }
他有一個get方法
scala> Some(100)
res15: Some[Int] = Some(100)
scala> Some(100).get
res16: Int = 100
元組(元組中不管有多少個值,他在函數式編程中都是一個變量)
scala> val tuple = (1,true,"xx",Unit)
tuple: (Int, Boolean, String, Unit.type) = (1,true,xx,object scala.Unit)
scala> tuple._3
res17: String = xx
scala> tuple._2
res18: Boolean = true
scala> tuple._4
res19: Unit.type = object scala.Unit
元組迭代器
scala> tuple.productIterator
res20: Iterator[Any] = non-empty iterator
scala> tuple.productIterator.toList
res21: List[Any] = List(1, true, xx, object scala.Unit)
scala> tuple.productIterator.foreach(println)
1
true
xx
object scala.Unit
對偶元組
scala> val tp1 = ("word", 4)
tp1: (String, Int) = (word,4)
scala> tp1.swap //交換元素 res30: (Int, String) = (4,word)