Scala允许函数调用语法
f(arg1, arg2,…) ⇒ f.apply(arg1, arg2,…)
f(arg1, arg2,…) = value ⇒ f.update(arg1, arg2,…) = value
例如:
val scores = new scala.collection.mutable.HashMap[String,Int]
socres("bob") = 100//调用scores.update("bob",100)
val bobscore = scores("bob")//scores.apply("bob")
Apply方法
apply方法同样被用在伴生对象中,来避免使用new来创建对象
例如:
// 该类存储一个分数
class Fraction(n: Int, d: Int) {
// 分子
private var num = if (d == 0) 1 else n * sign(d) / gcd(n,d)
// 分母
private var den = if (d == 0) 0 else d * sign(d) / gcd(n,d)
def sign(a: Int) = if (a > 0) 1 else if (a < 0) -1 else 0
// 返回化简之后的分数 3/9 = 1/3 ,-3/-9 = 1/3 ,3/-9 = -1/3
def gcd(a: Int, b: Int): Int = if (b == 0) abs(a) else gcd(b, a % b)
def abs(n: Int) = if (n > 0) n else -n
override def toString = num+"/"+den
// 调用apply
def *(o: Fraction) = Fraction(num * o.num, den * o.den)
def result = if(den!=0) num / den.toDouble else None
}
object Fraction {
// apply方法
def apply(num: Int, den: Int) = new Fraction(num, den)
// 提取器
def unapply(input: Fraction) =
if (input.den == 0) None else Some((input.num, input.den))
}
调用方式:
// 使用new调用函数
val f = new Fraction(3, 4)
val f3 = new Fraction(4, 5)
val f2 = f * f3
// 使用apply调用
val f6 = Fraction(3,4) * Fraction(4,5)
提取器unapply
val f5 = Fraction(3, 2) * Fraction(3, 2)
// 使用unapply方法从f5对象中提取分子分母
val Fraction(sum, den) = f5
// 获取提取结果(9,4,2.25)
println(sum, den, f5.result)
// 注意如果分母为0,该提取方法会报错 scala.MatchError: 1/0
// val Fraction(sum1,den1) = Fraction(1,0)
// 可以通过模式匹配来避免错误
m(Fraction(1,0))//None
def m(fac: Fraction) = fac match {
case Fraction(sum, den) => println(sum, den)
case _ => println(None)
}
如果要匹配多个值得话还可以使用unapplySeq方法
object Name {
// 提取器函数一定要加返回值类型Option 按照多行空格分割字符串
def unapplySeq(input: String): Option[Seq[String]] =
if (input.trim() == "") None else Some(input.trim.split("\\s+"))
}
object tet324 extends App {
def author(n: String) = n match {
case Name(first) => println(first.mkString(","))
case Name(first, last) => println(first.mkString(","))
case Name(first, last, three) => println(first.mkString(","))
case _ => println(None)
}
// 会分别根据空格数自动匹配上面4种情况
author("test")
author("te st")
author("t es t")
author("t e s t")
}