Please enable JavaScript.
Coggle requires JavaScript to display documents.
Scala Essential (OO (:red_flag::singleton object (companion object
…
Scala Essential
OO
Case Class
Scala会自动为case class 创建一个companion object : 一个包含了 apply 和 unapply 方法的 单例对象 。 apply 方法用来创建样例类的实例,而 unapply 需要被伴生对象实现,以使其成为提取器。
-
-
Extractor
An extractor in Scala is an object that has a method called unapply as one of its members.
The purpose of that unapply method is to match a value and take it apart.
-
-
Functional Programming
call by name / value
def first(x: Int, y: => Int) = x
def first(x: Int, y: Int) = x
first(1, loop) :red_cross:
:red_flag:Curring
Curring = turing a function that takes 2 args
into a function takes 1 arg
That function returns a function that consumes the second arg
def mul(x:Int, y:Int)=x*y
def mulOne(x:int) = (y:Int)=>x*y
mulOne(3)(4)
PartialFunction
Scala中的Partia Function是一个Trait,其的类型为PartialFunction[A,B],其中接收一个类型为A的参数,返回一个类型为B的结果。
-
Pattern Match
var pattern="([0-9]+) ([a-z]+)".r
"1111 scala" match{
case pattern(num, text) => println(num + " : " + text)
abstract class Expr
case class Var(name:String) extends Expr
case class Number(name:String) extends Expr
case class UnOp(name:String) extends Expr
case class BinOp(name:String) extends Expr
Syntactic sugar
update method
f(arg1, arg2...) = value
f.update(arg1, arg2..., value)
apply method
f(arg1, arg2...)
f.apply(arg1, arg2...)