scala 從頭越

一個綜合小例子, 要嚴格區分 函數與方法 , 與 java 不同html

/**
  * Scala 的值類型有 7 種
  * Byte
  * Char
  * Short
  * Int
  * Long
  * Float
  * Double
  */
import scala.collection.mutable.ArrayBuffer
object Demo {
    def main(args: Array[String]):Unit = {
        val res = add(f);
        val sex = "男"
        val gender = if("男".equals(sex)) 1 else 0
        println(gender)
        println(res)
        f2(5)
        f3(2,3)
        println(arr1.toBuffer)
        arr2 += 1;
        // 追加元組
        arr2 += (2,3,4)
        // 追加定常數組
        arr2 ++= Array(5,6,7)
        // 追加變長數組
        arr2 ++= ArrayBuffer(8,9,10)
        // 在指定位置插入 n 個 元素, n>=1    *args
        arr2.insert(0,-3,-2,-1)
       // 在指定位置 2  開始移除兩個元素
        arr2.remove(2,2)
        for(i <- 0 until arr2.length ){
          println(arr2(i))
        }
        println("*"*100)
        arr2.foreach(println)
        println("*"*100)
        val v_i = for(i <- (0 to arr2.length).reverse) yield i*10
        println(v_i.sum)
        map_1.getOrElse("python", -1)
    }

    def add(f:(Int ,Int)=>Int):Int = {
     f(3,4)
  }
  val f = (x:Int, y:Int) => x+y
  val f2 = (n:Int) =>{
    for (i <- 1 to n){
      println(i)
    }
  }
  val f3 = (n:Int, m:Int) =>{
    for(i <- 1 to n; j <- 1 until m if i != j){
        println(i*10+j)
    }
  }
  val arr1 : Array[Int] = new Array[Int](8)
  val arr3 = Array("java","scala","python")
  val arr2 = ArrayBuffer[Int]()

  val map_1 = Map("java"->1,"scala"->2,"python"->3)

  val arr4 =  Array(1,2,3)
  arr3.zip(arr4)


}


//  延遲變量

object SharkTest{

  def init():Unit={
    println("call init()")
  }

  def main(args: Array[String]) {
    lazy val res = init()
    for(arg <-args){
      println(arg)
    }
    println("in main...")
    println(res)

  }
}





object SharkTest{

  def main(args: Array[String]) {
    val list1 = List(3,2,1,4,5,8,7,9,6)
    val list2 = list1.map(_ * 2)
    val list_3 = list1.filter(_ % 2 == 0)
    val list_4 = list1.sorted
    val list5 = list_4.reverse
    val list_6 = list1.grouped(4)
    //  將 Iterator轉換爲 List
    val list_7 = list_6.toList
    val list_8 = List(List(1,2,3), List(4,5,6), List(7,8,9))
    // 將多個 list 壓扁
    val list_9 = list_8.flatten

    // 先 按照 空格 分割拆分後 再壓平
    val list_10 = List("java scala python array")
    val list_11 = list_10.flatMap(_.split("\\s+"))
    val list_12 = list_10.map(_.split("\\s+")).flatten

    // 並行計算求和
    val arr = Array(1,2,3,4,5,6,7,8,9,10)
    // parallel
    val res = arr.par.sum
    val res2 = arr.par.reduce((x,y) => x+y)
    // 有初始值,無特定順序  則 每次 值不必定  125  135 65
    val res3 = arr.par.fold(10)(_+_)

    // 摺疊 , 有初始值 (有特定值) 則 每次值 固定 65
    val res4 = arr.par.foldLeft(10)(_+_)

    // 聚合
    val list_13 = List(List(1,2,3), List(3,4,5), List(2), List(0))
    val res5 = list_13.flatMap(x=>x).reduce(_+_)
    // base = 0
    val res6 = list_13.aggregate(0)((base,y)=>base+y.sum,(x,y)=>x+y)
    println(res6)
    // 求並集
    val l1 = List(5,6,4,7)
    val l2 = List(1,2,3,4)
    val res7 = l1 union l2
    // 求交集
    val res8 = l1 intersect l2
    // 求差集
    val res9 = l1 diff l2
    

  }
}


### word count  小例子

object SharkTest{

  def main(args: Array[String]) {

    val lines = List("hello java hello python", "hello scala", "hello scala hello java hello scala")
    val words = lines.flatMap(_.split("\\s+"))
    val words_pair = words.map(x=>(x,1))
    println(words_pair)
    val mp = words_pair.groupBy(_._1)
    val res = mp.mapValues(l=>l.length)
    val res2 = res.toList.sortBy{case(k,v)=>v}
    /*
    * Map(scala -> 3, java -> 2, hello -> 6, python -> 1)
    * */
    //mp.reduce((key,value)=>value.length)
//    val it = words.groupBy(e=>e)
    println(res2.reverse)


  }
}

進入面向對象

/* 一個 源代碼文件能夠有多個 類與 多個 伴生對象 ,源文件的 名字也不用 與 class 保持一致,pulic 類修飾符 也不用,默認 public*/
class Person {
  // 用 val 修飾的變量是隻讀的,至關於只有 get 方法, 沒有 set 方法
  val name : String = _
  // 用 var 修飾的變量至關於既有 get 方法, 又有 set 方法
  var race: String = _
  // 用 private 修飾的 變量 屬於私有變量 ,僅可在 本類與 伴生對象中 訪問
  private val id : Int = _
  // private 並添加 [this]  限定後 ,這個 變量 就只能在 本類訪問, 連伴生對象 都沒法訪問
  private[this] val gender = _

}

object Person{

  def main(args: Array[String]): Unit ={
    val person = new Person()


  }

}

模式匹配

object Demo{
    def main(args:Array[String]):Unit={
    val arr = Array("zhoudongyu","zhengshuang","guanxiaotong","yangzi")
        matchCase(arr)
    }
    def matchCase(arr:Array[String]):Unit={
    val name = arr(2)
        println("name: "+name)
        name match{
        case "zhoudongyu" => println("周冬雨")
            case "zhengshuang" => println("鄭爽")
            case "guanxiaotong" => println("關曉彤")
            case "yangzi" => println("楊紫")
            case _ => println("unknown")
        }
    }
}



  private val func : PartialFunction[Int,String]= {
    case 1 => "one"
    case 2 => "two"
    case 3 => "three"
    case _ => "others"
  }
  private val func2: Int=>String = x => x match{
    case 1 => "one"
    case 2 => "two"
    case 3 => "three"
    case _ => "others"
  }





柯里化

scala 自帶的 隱式轉換
在交互式窗口
:implicit -v


// 自定義 隱式轉換
package day04
class RichFile(file:String) {
  def read():String={
    Source.fromFile(file).mkString
  }

object MyFile {
  implicit def richFile(file:String) = new RichFile(file)
}



import day04.MyFile
    val file:String=""
    val content:String = MyFile.richFile(file).read()

這個隱式 好難理解

object ImplicitContext{
  implicit object OrderingGirl extends Ordering[Girl]{
    override def compare(x: Girl, y: Girl): Int = if(x.faceValue > y.faceValue) 1 else -1
  }
}

class Girl(val name:String, var faceValue:Int){}

class Goddess[T: Ordering](val g1:T, val g2:T){
  def choose()(implicit ord: Ordering[T]) = if (ord.gt(g1,g2)) g1 else g2
}

object Goddess {
  def main(args:Array[String]):Unit={
    import ImplicitContext.OrderingGirl
    val g1 = new Girl("大佬",90)
    val g2 = new Girl("小佬",80)
    val goddess = new Goddess(g1,g2)
    print(goddess.choose().name+"--"+goddess.choose().faceValue)
  }
}

附 學習資源

水滴產品團隊
面向 Scala 的技術博客
https://scala.cool/
https://scala.cool/tags/%E4%BB%8E-Java-%E5%88%B0-Scala/
https://scala.cool/tags/Scala-%E7%B1%BB%E5%9E%8B%E7%9A%84%E7%B1%BB%E5%9E%8B/
Scala 課堂!
http://twitter.github.io/scala_school/zh_cn/
優秀我的博客
http://hongjiang.info/scala/
Effective Scala
http://twitter.github.io/effectivescala/index-cn.html
官網
https://docs.scala-lang.org/
api
https://docs.scala-lang.org/api/all.htmljava

相關文章
相關標籤/搜索