1. 程式人生 > >Scala基礎快速學習筆記

Scala基礎快速學習筆記

Scala
--------------
    Java語言指令碼化
    面向函式:直奔主題
    直接寫程式,直接執行即可。
進入Scala shell
-----------------
$>bin/scala
$scala>:help  //檢視幫助

o.getClass();

classOf(res6)
inter::型別推斷

Int             -->RichInt
Double          -->RichDouble
Char            -->RichChar


scala                  java
-----------------------------
Int                    int+Integer
val(value)           final:常量
var                    可以修改(變數)
var x :String = "hello"
Any(任意)區分大小寫     Object
1.toString()//自動1->Integer

1.to(10)      //方法
1.to 10       //操作符

使用函式進行資料型別轉換
var a:Int = 100;
var b:Short = 100;
b = (Short)a  //error
b = a.toShort //ok

++ / --       //error,不支援
+=      | -=  //ok

函式  |  方法
----------------------
函式:不需要通過類即可直接呼叫方法。min power
import scala.math._   "_"類似"*"
sqrt(2)           //開方
pow(n)            //幾次方

單例物件
--------------


class Xxxx{
    。。
}
object Xxxx{

}

REPL : read + eval + print + loop


無參的函式使用時可以省略()
----------------------------------
    $scala>1.toString()
    &scala>1,toString

apply
----------------------------------
  1.$scala>"hello"(4)             //String.chatAt(i)
  2.$scala>"hello".apply(4)       //String.chatAt(i)
  3.$scala>BigInt("1234")         //BigInt.apply("1234567")


控制結構 + 函式
---------------------------------
1.條件表示式(if else)有值
2.三元運算子
。。。
val y = if(x>0) 1
val y = if(x>0) 1 else()            //() == 不存在的  (unit === void)
3.進入shell的貼上模式
$scala>:paste
$scala>                            //CTRL + D
句尾不需要分號,單行中寫入多條語句需要用分號隔開
4.列印
  print("hello")
  println("hello")
5.可以使用readLine從控制檯讀取一行輸入
  readLine("xxx")                 //字串
  readLine("age")                 //Int
6.迴圈:與c++,java一樣的while迴圈
[while]
var i = 0;
while(i<10){
| i=i+1;
| println(i)
}
[for]
for(i <- 1 to 10){
|  print(i)
|}

for(i <- 1 until 10){println(i)}

Map + reduce
----------------------
map()  :

scala break操作
Scala沒有提供break和continue語句來退出迴圈
可以用breakable塊
import scala.util.control.Breaks._

breakable{
    for(i <- 1 to 10){
    if(i<5) println(i) else break;
    }
}


[a.scala]
$scala>load /home/ubuntu/a.scala

高階for迴圈,列印正三角形9*9表格
----------------------------------
for(i <- 1 to 9;j <- 1 to 9){
    if(i >= j) print(i + "x" + j + "=" + (i + j) + " ")
if(j==i) println()
}

yield(產生)
-----------------------
每次迴圈期間,每次產生新值放入集合中
 var x = for(i <- 1 to 10) yield i % 3
 x: scala.collection.immutable.IndexedSeq[int] = Vector(1,2,0,1,2,0,1,2,0,1)

函式不需要呼叫但是方法必須呼叫

函式,遞迴函式必須宣告返回型別。
----------------
[定義]
def abs(x:Double) = if (x >= 0) x else -x
def fname(pname:ptype) : retype = body
def add(a:Int,b:Int) : Int = a + b

[階乘函式(迴圈方式)]
def fac(n:Int) = {
    var r = 1;
    for(i <- 1 to n)r = r * i
    r
    }
[階乘函式(遞迴方式)]
def fac(n:Int) : Int = {
    if(n == 1) 1 else fac(n-1)*n
}

fac(6) = 6 * fac(5) ==> 6 * 5 * fac(4)==>..

apply
----------------------
 "xxx"(4)             //"xxx".apply(4)


預設引數值,帶名引數
-------------------------

   public String xxx(String a,String b = "xxx"){
    ...
}


$scala>def dec(a:String,left:String = "[",right:String="]") : String = left + a + right
$scala>var x = dec("tom")                                  //x = [tom]           //預設值
$scala>var x =dec(a="tom",right="###")                     //x = [tom]           //指名引數


變長引數
-----------------------
def sum(args:Int*) = {
    var x = 0;
    for(i <- args) r =r + i
    r
}
$scala>var x = sum(1,2,3,4,5);
$scala>var x = sum(1 to 5)                                     //error,型別不匹配
$scala>var x = sum(1 to 5:_*)   加上":_*"轉換成引數序列。

1 to n            //Range區間,不是Seq

def rsum(args:Int*):Int = {
if(args.length == 0) 0
else args.head + rsum(args.tail:_*)
}

instanceOf
getClass() == Xxx.class

過程,不返回值的函式,不使用 = 附作用
------------------------------
def box(name:String){
    println("$$$" + name + "$$$")
}


def box(name:String): Unit = {
    println("$$$" + name + "$$$")
}


lazy value:延遲求值
-----------------------
$scala>lazy val x = scala.io.source.FromFile("/xx/x/x/").mkString                 //延遲求值
$scala>x


異常
-------------------
java : Throwable Error() + Exception(RuntimeException)
public void add(...){
    try{

    }
    
    catch(X1Exception e1){
        e1
    }
    catch(X2Exception e2){
    }
}    


checked                    //待檢
managed                    //託管

try{
    。。。
}
catch{
    case_ : XxxxException => xxx                                 //進入xxx處理程式
    case ex : XxxxException => ex.printStackTrace()              //進入xxx處理程式 
                                                                     //越具體的異常越靠前  
}

陣列 + 緩衝區
---------------------
int[]
ByteBuffer

$scala>val x = new Array[Int](10)    //0.0.0.0.....
$scala>val x = new Array[String](10)null,null,null,....
$scala>var x = Array("hello" + "world")
$scala>x(3)                                       //方法陣列元素 

ArrayBuffer                                      //陣列緩衝區
$scala> scala.collection.mutable.ArrayBuffer
scala>var x = ArrayBuffer[Int]()
scala>x ++= Array(1,2,3)                        //使用++=操縱任何集合
scala>x.trimEnd(5)                                //移除最右的n個元素
scala>x.insert(2,3,4,5,6)                                          //在2位置插入3.。。
scala>x.remove(2,3)                                                //從2開始移除,移除3個
scala>x.remove(2)                                                  //x.remove(2,1)
scala>buffer.toArray                                               //從buffer到Array之間的轉換
scala>array.toBuffer                                               //..

scala>for(i <- buffer | array) .. //遍歷buffer|array

//yield遍歷過程中,生成新的集合
scala>for(i <- 1 to 5 if i % 2 == 0) yield i * 2                  //先filter,再乘以2產生新集合
scala>var x = Array(1 to 5)

//內建函式
scala>Array(1,2,3).sum

//緩衝區排序
scala>y.sorted(_<_)                                               //升序排序

//快速排序
Scala>var x = Array(1,7,2,9)
scala>scala.util.Sorting.quickSort(a)                            

//mkString
scala>a.mkString("and")

多維陣列
----------------
int[層][行][列] cube                                            //java
Array[Array[Array[Int]]]                                        //scala
scala>var x = Array.ofDim[Int](3,3,3)                           //三維陣列
scala>var idx = 1;
for(i <- 0 until x.length){
    for(j <- 0 until x(i).length){
        for(k <- 0 until x(i)(j).length){
        x(i)(j)(k) = idx ;
        idx += 1
        }
    }
}


//使用不等長元素的多維陣列
scala>var x = new Array[Array[Int]](4)

java和scala的互操作
-------------------------------
。。。。。

map  tuple(映像和元組)
-----------------------
1.java.util.Map
  java.util.HashMap
  java.util.TreeMap
2.var map = Map("001"->"tom","002"->"tomas","003"->"tomasLee")
3.var map = collection.mutable.Map("001"->"tom","002"->"tomas","003"->"tomasLee")
4.map("001")       //get
  map.contais("001")   //判斷是否存在
  map.getOrElse("001","nobody")  //組合
  map("001") = "xxx"     //賦值
5.map2 - "004"   //支援


迭代
---------
scala>for((k,v)<-map)println(k + "-----" + v)   //遍歷

Java
---------
map.keySet()    //key集合
map.values()    //value集合

排序map
------------
scala>import scala.collection.immutable.SortedMap


實現java和scala之間map的互相轉換
scala>var m :scala.collection.mutable.Map[String,String]


tuple(元組)
-----------------------
元組,Map是有兩個元素的元組
元組最多支援22元素
TupleX
scala>var t : Tuple3[Int,String,Int] = (1,"tom",12)       //tuple
scala>t._1              //n從1開始
scala>val (id,name,age) = t
scala>id
scala>name
scala>age


zip:咬合操作
--------------------
兩個陣列的元素一一組合。
scala>var ids = Array("001","002","003")
scala>var names = Array("tom","tomas","tomasLee")
scala>var pairs = ids.zip(names)



-------------
 1.class Classname{
    private var id = 0;    //必須初始化,否者需要聲名成abstract
}
2.class Counter{
    private var value = 0
    def increment() = value += 1
    def current() = value
    }
3.getter和 setter

    getter  //age
    setter  //age=
4.Dog           //可以更加豐富的控制可見性
    class Dog{
        private[this] var value = 0
        def addOne() = {age += 1}
        def compare(b:Dog) = {age < b.age}
        }


    class Counter{
    privte var value = 0
    def increment() = value += 1
    def current() = value
    }


5. scala.beans.BeanProperty
    class Dog{
        @BeanProperty private var age = 0    //生成getter  /  setter
    def addOne() = {age += 1}
    def compare(b:Dog)={age < b.age}
}
6.輔助建構函式
    class Dog{
        ...
        def this(name:String){
        this()               //主構造
        this.name = name     //賦值

    如果主建構函式的引數使用了var或val,他們會生成對應的欄位。如果沒有使用的話,但在方法中進行了訪問,自動升級成欄位。

7.java建構函式的第一條構造語句
    class Dog{
        public Dog(){
            this.
            }
        }


8.巢狀類(內部類)
    class Car{
        class Engine{
        }
    }

物件Object        
---------------------
   1.定義單例物件
    [Box.scala]
    object Box{
        def getColor = "yellow"
    }


    [Box.class]
    fine class Box{
        public static String getColor();
    }

class Counter{
private var value = 0;
def increment() = value += 1
def current() = value
}