摘自官网

variables  
var x = 5

Good

x = 6
Variable.
val x = 5

Bad

x = 6
Constant.
var x: Double = 5
Explicit type.
functions  
Good

def f(x: Int) = { x * x }

Bad

def f(x: Int)   { x * x }
Define function.
Hidden error: without = it’s a procedure returning Unit; causes havoc. Deprecated in Scala 2.13.
Good

def f(x: Any) = println(x)

Bad

def f(x) = println(x)
Define function.
Syntax error: need types for every arg.
type R = Double
Type alias.
def f(x: R)

vs.

def f(x: => R)
Call-by-value.

Call-by-name (lazy parameters).

(x: R) => x * x
Anonymous function.
(1 to 5).map(_ * 2)

vs.

(1 to 5).reduceLeft(_ + _)
Anonymous function: underscore is positionally matched arg.
(1 to 5).map(x => x * x)
Anonymous function: to use an arg twice, have to name it.
(1 to 5).map { x =>
val y = x * 2
println(y)
y
}
Anonymous function: block style returns last expression.
(1 to 5) filter {
_ % 2 == 0
} map {
_ * 2
}
Anonymous functions: pipeline style (or parens too).
def compose(g: R => R, h: R => R) =
(x: R) => g(h(x))
val f = compose(_ * 2, _ - 1)
Anonymous functions: to pass in multiple blocks, need outer parens.
val zscore =
(mean: R, sd: R) =>
(x: R) =>
(x - mean) / sd
Currying, obvious syntax.
def zscore(mean: R, sd: R) =
(x: R) =>
(x - mean) / sd
Currying, obvious syntax.
def zscore(mean: R, sd: R)(x: R) =
(x - mean) / sd
Currying, sugar syntax. But then:
val normer =
zscore(7, 0.4) _
Need trailing underscore to get the partial, only for the sugar version.
def mapmake[T](g: T => T)(seq: List[T]) =
seq.map(g)
Generic type.
5.+(3); 5 + 3
(1 to 5) map (_ * 2)
Infix sugar.
def sum(args: Int*) =
args.reduceLeft(_+_)
Varargs.
packages  
import scala.collection._
Wildcard import.
import scala.collection.Vector
import scala.collection.{Vector, Sequence}
Selective import.
import scala.collection.{Vector => Vec28}
Renaming import.
import java.util.{Date => _, _}
Import all from java.util except Date.
At start of file:

package pkg

Packaging by scope:

package pkg {
...
}

Package singleton:

package object pkg {
...
}
Declare a package.
data structures  
(1, 2, 3)
Tuple literal (Tuple3).
var (x, y, z) = (1, 2, 3)
Destructuring bind: tuple unpacking via pattern matching.
Bad

var x, y, z = (1, 2, 3)
Hidden error: each assigned to the entire tuple.
var xs = List(1, 2, 3)
List (immutable).
xs(2)
Paren indexing (slides).
1 :: List(2, 3)
Cons.
1 to 5

same as

1 until 6
1 to 10 by 2
Range sugar.
()
Empty parens is singleton value of the Unit type.
Equivalent to void in C and Java.
control constructs  
if (check) happy else sad
Conditional.
if (check) happy

same as

if (check) happy else ()
Conditional sugar.
while (x < 5) {
println(x)
x += 1
}
While loop.
do {
println(x)
x += 1
} while (x < 5)
Do-while loop.
import scala.util.control.Breaks._

breakable {
for (x <- xs) {
if (Math.random < 0.1)
break
}
}
Break (slides).
for (x <- xs if x % 2 == 0)
yield x * 10

same as

xs.filter(_ % 2 == 0).map(_ * 10)
For-comprehension: filter/map.
for ((x, y) <- xs zip ys)
yield x * y

same as

(xs zip ys) map {
case (x, y) => x * y
}
For-comprehension: destructuring bind.
for (x <- xs; y <- ys)
yield x * y

same as

xs flatMap { x =>
ys map { y =>
x * y
}
}
For-comprehension: cross product.
for (x <- xs; y <- ys) {
val div = x / y.toFloat
println("%d/%d = %.1f".format(x, y, div))
}
For-comprehension: imperative-ish.
sprintf style.
for (i <- 1 to 5) {
println(i)
}
For-comprehension: iterate including the upper bound.
for (i <- 1 until 5) {
println(i)
}
For-comprehension: iterate omitting the upper bound.
pattern matching  
Good

(xs zip ys) map {
case (x, y) => x * y
}

Bad

(xs zip ys) map {
(x, y) => x * y
}
Use case in function args for pattern matching.
Bad

val v42 = 42
3 match {
case v42 => println("42")
case _ => println("Not 42")
}
v42 is interpreted as a name matching any Int value, and “42” is printed.
Good

val v42 = 42
3 match {
case `v42` => println("42")
case _ => println("Not 42")
}
`v42` with backticks is interpreted as the existing val v42, and “Not 42” is printed.
Good

val UppercaseVal = 42
3 match {
case UppercaseVal => println("42")
case _ => println("Not 42")
}
UppercaseVal is treated as an existing val, rather than a new pattern variable, because it starts with an uppercase letter. Thus, the value contained within UppercaseVal is checked against 3, and “Not 42” is printed.
object orientation  
class C(x: R)
Constructor params - x is only available in class body.
class C(val x: R)
var c = new C(4)
c.x
Constructor params - automatic public member defined.
class C(var x: R) {
assert(x > 0, "positive please")
var y = x
val readonly = 5
private var secret = 1
def this = this(42)
}
Constructor is class body.
Declare a public member.
Declare a gettable but not settable member.
Declare a private member.
Alternative constructor.
new {
...
}
Anonymous class.
abstract class D { ... }
Define an abstract class (non-createable).
class C extends D { ... }
Define an inherited class.
class D(var x: R)
class C(x: R) extends D(x)
Inheritance and constructor params (wishlist: automatically pass-up params by default).
object O extends D { ... }
Define a singleton (module-like).
trait T { ... }
class C extends T { ... }
class C extends D with T { ... }
Traits.
Interfaces-with-implementation. No constructor params. mixin-able.
trait T1; trait T2
class C extends T1 with T2
class C extends D with T1 with T2
Multiple traits.
class C extends D { override def f = ...}
Must declare method overrides.
new java.io.File("f")
Create object.
Bad

new List[Int]

Good

List(1, 2, 3)
Type error: abstract type.
Instead, convention: callable factory shadowing the type.
classOf[String]
Class literal.
x.isInstanceOf[String]
Type check (runtime).
x.asInstanceOf[String]
Type cast (runtime).
x: String
Ascription (compile time).  
options  
Some(42)
Construct a non empty optional value.
None
The singleton empty optional value.
Option(null) == None
Option(obj.unsafeMethod)

but

Some(null) != None
Null-safe optional value factory.
val optStr: Option[String] = None

same as

val optStr = Option.empty[String]
Explicit type for empty optional value.
Factory for empty optional value.
val name: Option[String] =
request.getParameter("name")
val upper = name.map {
_.trim
} filter {
_.length != 0
} map {
_.toUpperCase
}
println(upper.getOrElse(""))
Pipeline style.
val upper = for {
name <- request.getParameter("name")
trimmed <- Some(name.trim)
if trimmed.length != 0
upper <- Some(trimmed.toUpperCase)
} yield upper
println(upper.getOrElse(""))
For-comprehension syntax.
option.map(f(_))

same as

option match {
case Some(x) => Some(f(x))
case None => None
}
Apply a function on the optional value.
option.flatMap(f(_))

same as

option match {
case Some(x) => f(x)
case None => None
}
Same as map but function must return an optional value.
optionOfOption.flatten

same as

optionOfOption match {
case Some(Some(x)) => Some(x)
case _ => None
}
Extract nested option.
option.foreach(f(_))

same as

option match {
case Some(x) => f(x)
case None => ()
}
Apply a procedure on optional value.
option.fold(y)(f(_))

same as

option match {
case Some(x) => f(x)
case None => y
}
Apply function on optional value, return default if empty.
option.collect {
case x => ...
}

same as

option match {
case Some(x) if f.isDefinedAt(x) => ...
case Some(_) => None
case None => None
}
Apply partial pattern match on optional value.
option.isDefined

same as

option match {
case Some(_) => true
case None => false
}
true if not empty.
option.isEmpty

same as

option match {
case Some(_) => false
case None => true
}
true if empty.
option.nonEmpty

same as

option match {
case Some(_) => true
case None => false
}
true if not empty.
option.size

same as

option match {
case Some(_) => 1
case None => 0
}
0 if empty, otherwise 1.
option.orElse(Some(y))

same as

option match {
case Some(x) => Some(x)
case None => Some(y)
}
Evaluate and return alternate optional value if empty.
option.getOrElse(y)

same as

option match {
case Some(x) => x
case None => y
}
Evaluate and return default value if empty.
option.get

same as

option match {
case Some(x) => x
case None => throw new Exception
}
Return value, throw exception if empty.
option.orNull

same as

option match {
case Some(x) => x
case None => null
}
Return value, null if empty.
option.filter(f)

same as

option match {
case Some(x) if f(x) => Some(x)
case _ => None
}
Optional value satisfies predicate.
option.filterNot(f(_))

same as

option match {
case Some(x) if !f(x) => Some(x)
case _ => None
}
Optional value doesn't satisfy predicate.
option.exists(f(_))

same as

option match {
case Some(x) if f(x) => true
case Some(_) => false
case None => false
}
Apply predicate on optional value or false if empty.
option.forall(f(_))

same as

option match {
case Some(x) if f(x) => true
case Some(_) => false
case None => true
}
Apply predicate on optional value or true if empty.
option.contains(y)

same as

option match {
case Some(x) => x == y
case None => false
}

scala 语法速查的更多相关文章

  1. Markdown 语法速查表

      Markdown 语法速查表 1 标题与文字格式 标题 # 这是 H1 <一级标题> ## 这是 H2 <二级标题> ###### 这是 H6 <六级标题> 文 ...

  2. Python语法速查: 4. 字符串常用操作

    返回目录 (1)字符串常用方法 Python3中,字符串全都用Unicode形式,所以省去了很多以前各种转换与声明的麻烦.字符串属于序列,所有序列可用的方法(比如切片等)都可用于字符串. 注意:字符串 ...

  3. Python语法速查:目录

    1. 数据类型与内置函数 2. 列表.元组.字典.集合操作 3. 字符串格式化 4. 字符串常用操作 5. 运算符.math模块.表达式 6. 循环与迭代 7. 函数基础 8. 类与对象 9. 函数进 ...

  4. IE各版本CSS Hack(兼容性处理)语法速查表

    为了兼容IE各个版本,需要在CSS中添加额外的代码,比如以前常用的_width.之所以工作,是因为浏览器会忽略不能解析的样式规则,因此举个例子来说,把_width写在width下面,对于非IE浏览器会 ...

  5. perl 语法速查

    同时学perl.python和shell脚本会很容易将它们的语法搞混,本文主要是一个个人的总结,方便要用时的查询. perl基本语法.安装.帮助文档 文件头格式: #!/usr/bin/perl us ...

  6. xpath语法速查

    xpath的具体学习可以通过w3c查看(链接:http://www.w3school.com.cn/xpath/index.asp) 这里只是将平时用到的几个表格贴出来,以后查询: 这里的xpath我 ...

  7. Transact-SQL语法速查手册

    第1章 Transact-SQL基础 1.1 标识符 一.常规标识符 1. 命名规则: l 第一个字母必须是Unicode2.0标准定义的字母.下划线.at符号(@)和数字符号(#): l 后续字符可 ...

  8. Python语法速查: 15. 常用数据结构

    返回目录 本篇索引 (1)array (2)bisect (3)deque (4)defaultdict (5)namedtuple (6)heapq (7)itertools (1)array ar ...

  9. Python语法速查: 13. 操作系统服务

    返回目录 本篇索引 (1)sys模块 (2)os模块 (3)与Windows相关模块 (4)subprocess模块 (5)signal模块 (1)sys模块 sys模块用于Python解释器及其环境 ...

随机推荐

  1. 持续集成与Devops关系

    什么是持续集成 持续集成(Continuous Integration,简称CI),是一种软件开发实践,在实践中指只要代码有变更,就自动运行构建和测试,反馈运行结果.通俗一点来讲,就是绑定项目的代码仓 ...

  2. Nuget使用时遇到的问题,Solved

    在VS的程序包管理控制台中输入Install-package MySql.Data时,默认安装最新的版本8.0.18, 但是安装完成后,发现包并没有添加到项目的引用列表中, 在解决方案的package ...

  3. 工作日志,go get -v -x github.com/pebbe/zmq4 失败问题

    工作日志,go get -v -x github.com/pebbe/zmq4 失败问题 笔者因为工作需要使用ZeroMQ,但是在执行go get -v -x github.com/pebbe/zmq ...

  4. centos7.6使用openssl生成CA签署的证书个人实验笔记

    准备:客户端centos6.10  服务端Centos7.6 实验:客户端生成证书请求,服务端颁发证书,最后吊销其中一个证书 1.先在服务端上的/etc/pki/CA/目录生成rsa的私钥: 2.在服 ...

  5. appium---App页面滑动

    我们操作app的过程中都会进行页面滑动,那么这个过程通过python怎么实现呢? 如何滑动 大家都非常的清楚我们手动在app上是如何滑动的,然后自动化只是模仿了手工的方法去实现,我们通过一个图来分析 ...

  6. Make Them Odd

    time limit per test3 secondsmemory limit per test256 megabytesinput: standard inputoutput: standard ...

  7. Noip2015Day2T3 运输计划

    题目链接 problem 一棵n个点带边权的树,有m个条路径.选择一条边,将其权值变为0,使得长度最长的路径长度最小.求该长度最小为多少. solution 其实仔细一想并不难. 删除一条边会导致所有 ...

  8. Noip2018Day1T3 赛道修建

    题目链接 problem 给出一棵有边权的树.一条链的权值定义为该链所经过的边的边权值和.需要选出\(m\)条链,求\(m\)条链中权值最小的链的权值最大是多少. solution 首先显然二分. 然 ...

  9. Educational Codeforces Round 76 (Rated for Div. 2) E. The Contest dp

    E. The Contest A team of three programmers is going to play a contest. The contest consists of

  10. CF582E Boolean Function(DP,状态压缩,FMT)

    简单题. 我第二道自己做出来的 2900 没毛病,我没切过 2800 的题 lqy:"CF 评分 2800 是中等难度" 我活个啥劲啊 为了方便(同时压缩状态个数),先建出表达式树 ...