Scala入门篇 顶

2019-08-21 17:15:25 浏览数 (1)

1、定义变量

var 可变

val 不可变,相当于Java中的final

Unit相当于Java中的void,以()表示

scala> val a = println("ddd") ddd a: Unit = ()

2,声明数组

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 5

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

代码语言:javascript复制
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元

代码语言:javascript复制
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,可变参数以及参数的默认值

代码语言:javascript复制
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函数中.

代码语言:javascript复制
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

代码语言:javascript复制
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,偏函数

代码语言:javascript复制
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映射

代码语言:javascript复制
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)

代码语言:javascript复制
/**
  * 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是一个样例类

代码语言:javascript复制
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)

0 人点赞