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() // 此步出错又如何处理? }