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 = 1234567890x * x * x // Java 需要调用方法 x.multiply(x).multiply(x)_ 代表通配符,可表达任意东西import scala.math._ 导入数学函数包)import scala.math._ 可写为 import math._"Hello".distinctapply 方法
()"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 表达式,而是使用更为强大的模式匹配来替代语句块&赋值
{...} 包含一系列表达式,语句块的结果为最后一个表达式的结果val a = { express1; express2; express3 }x=y=1 // 与预期结果不一致IO
print / println / printfreadLine / readInt / readDouble...循环
for(init; test; update),可使用 while 代替,或者使用 for 表达式
for (i <- 1 to 10) r = r * ivariable <- 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)函数
trait Function... 的实例technically is an object with an apply methoddef abs(x: Double) = if (x >= 0) x else -x=右边的表达式或语句块的最后一个表达式的结果;可省略 returndef fac(n: Int): Int = if (n <= 0) 1 else n * fac(n - 1)def decorate(str: String, left: String = "[", right: String = "]") = left + str + rightdecorate("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过程 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() // 此步出错又如何处理?
}原文:https://www.cnblogs.com/yuanzam/p/11605521.html