1.toString()
1.to(10)
// Range(1,2,3,4,5,6,7,8,9,10)"Hello".intersect("World")
// "lo"1 + 2
等價於 1.+(b)
a.method(b)
可簡寫爲 a method b
++
和 --
操做,使用 +=1
和 -=1
代替val x: BigInt = 1234567890
x * x * x
// Java 須要調用方法 x.multiply(x).multiply(x)
_
表明通配符,可表達任意東西import scala.math._
導入數學函數包)import scala.math._
可寫爲 import math._
"Hello".distinct
apply
方法
()
"Hello"(4)
等價於 "Hello".apply(4)
if/else
表達式有返回值
val s = if (a > 0) 1 else -1
// 這種方式下 s 定義爲 val,若是放到判斷內部賦值,須要定義爲變量 var?:
和 if/else
;Scala 無三目運算if (a) 1
等價於 if (a) 1 else ()
;能夠將 ()
(,即 Unit 類) 視爲無用值的佔位符,可看作 Java 中的 voidswitch
表達式,而是使用更爲強大的模式匹配來替代語句塊&賦值java
{...}
包含一系列表達式,語句塊的結果爲最後一個表達式的結果val a = { express1; express2; express3 }
x=y=1
// 與預期結果不一致IOexpress
print / println / printf
readLine / readInt / readDouble...
循環app
for(init; test; update)
,可以使用 while 代替,或者使用 for 表達式
for (i <- 1 to 10) r = r * i
variable <- expression
會遍歷全部元素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 } }
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)函數scala
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")
// <adef sum(args: Int*) ={var result=0; for (a <- args) result += a; result}
sum(1,2,3)
// 6sum(1 to 5: _*)
// 15 當傳遞序列作爲參數時,須要添加 _*
告訴編譯器傳入的爲參數序列, 而不是 Int過程 Procedurescode
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 語句塊中可以使用模式匹配來處理對應類型的異常ip
try { process(xx) } catch { // 優先匹配原則,將最準確的匹配項放在前面,通用的匹配項放在最後 case ex: IOException => do1() case _ => None }
使用 try/finally 來忽略異常ci
preStep() // 此步出錯如何處理? try { process(oo) } finally { f() // 此步出錯又如何處理? }