scala 的apply,update,unapply方法

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")
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值