Scala 中數據類型也是 classjava
原始類型與 class 類型無區別,可在數字上調用方法(隱式轉換爲對應的方法調用,如對 Int 操做轉爲 RichInt 的方法調用等)express
1.toString()
1.to(10)
// Range(1,2,3,4,5,6,7,8,9,10)隱式轉換的 StringOps 對 String 擴展,包含了上百種操做app
"Hello".intersect("World")
// "lo"操做符重載,算數操做符也是方法函數
1 + 2
等價於 1.+(b)
a.method(b)
可簡寫爲 a method b
++
和 --
操做,使用 +=1
和 -=1
代替BigInt 和 BigDecimal 也可直接使用算數運算符scala
val x: BigInt = 1234567890
x * x * x
// Java 須要調用方法 x.multiply(x).multiply(x)
_
表明通配符,可表達任意東西import scala.math._
導入數學函數包)import scala.math._
可寫爲 import math._
無參方法調用時一般不須要帶括號code
"Hello".distinct
apply
方法對象
()
"Hello"(4)
等價於 "Hello".apply(4)
條件表達式遞歸
if/else
表達式有返回值ip
val s = if (a > 0) 1 else -1
// 這種方式下 s 定義爲 val,若是放到判斷內部賦值,須要定義爲變量 var?:
和 if/else
;Scala 無三目運算if (a) 1
等價於 if (a) 1 else ()
;能夠將 ()
(,即 Unit 類) 視爲無用值的佔位符,可看作 Java 中的 voidswitch
表達式,而是使用更爲強大的模式匹配來替代語句終結ci
語句塊&賦值
{...}
包含一系列表達式,語句塊的結果爲最後一個表達式的結果可用於初始化須要多步操做的值
val a = { express1; express2; express3 }
x=y=1
// 與預期結果不一致IO
print / println / printf
readLine / readInt / readDouble...
循環
沒有與 Java 相似的 for 循環 for(init; test; update)
,可以使用 while 代替,或者使用 for 表達式
for (i <- 1 to 10) r = r * i
variable <- expression
會遍歷全部元素for 循環可包含多個生成器,逗號分隔(或換行區分),可以使用 parttern guard 來進行條件過濾
for(v <- exp1; v2 <- exp2 if(condition)) doSome()
// if 以前的分號可省略1 to n
包含上界,1 until n
不包含上界沒有 break,continue 表達式來中斷循環,替代方案:
import scala.util.control.Breaks._ breakable { for (...) { if (...) break } }
yield,在 for 循環體以 yield 開始的形式成爲 for 推導式
產生的結果爲每次迭代的值的集合
for(i <- 1 to 3) yield i % 3
// Vector(1, 2, 0)生成的集合與第一個生成器類型一致
for(c <- "hello"; i <- 0 to 1) yield (c+i).toChar
// hieflmlmopfor(i <- 0 to 1; c <- "hello") yield (c+i).toChar
// Vector(h, e, l, l, o, i, f, m, m, p)函數
trait Function...
的實例technically is an object with an apply method
def abs(x: Double) = if (x >= 0) x else -x
=
右邊的表達式或語句塊的最後一個表達式的結果;可省略 return
若是是遞歸函數,則必須指明返回類型
def fac(n: Int): Int = if (n <= 0) 1 else n * fac(n - 1)
參數默認值和命名參數
def decorate(str: String, left: String = "[", right: String = "]") = left + str + right
調用時可給部分參數,也可給所有參數,還可經過命名參數傳值而不考慮參數順序
decorate("a")
// [a]decorate("a", "<<")
// <<a]decorate(left="<", "a")
// <a可變參數(本質上是一個 Seq 類型的參數)
def sum(args: Int*) ={var result=0; for (a <- args) result += a; result}
sum(1,2,3)
// 6sum(1 to 5: _*)
// 15 當傳遞序列作爲參數時,須要添加 _*
告訴編譯器傳入的爲參數序列, 而不是 Int過程 Procedures
def box(s: String) { println(s) }
// 無須要 =
lazy
lazy val words = scala.io.Source.fromFile("/../words").mkString
// if the program never accesses words
, the file is never openedExceptions
Nothing
,throw 表達式的返回類型;在 if/else 表達式中,若是一個分支拋出異常,則 if/else 的返回類型爲另外一個分支的類型
if (x > 0) f(x) else throw new Exception("xx")
catch 語句塊中可以使用模式匹配來處理對應類型的異常
try { process(xx) } catch { // 優先匹配原則,將最準確的匹配項放在前面,通用的匹配項放在最後 case ex: IOException => do1() case _ => None }
使用 try/finally 來忽略異常
preStep() // 此步出錯如何處理? try { process(oo) } finally { f() // 此步出錯又如何處理? }