scala 随笔(7)unapply 解析



apply he unapply 都是放在object 半生类里面。
apply 可以用来new对象,
unapply能够解析对象。一般与match 联合使用
class UnapplyTest (var x :String ,var y :Int) {

}
object UnapplyTest {
  def apply(x:String): UnapplyTest ={
    val array =  x.split(":")
    require(array.length==2)
    new UnapplyTest(array(0).toString,array(1).toInt)
  }

  def unapply(unapplyTest: String): Option[(String,Int)]={
    val array =  unapplyTest.split(":")
    Some(array(0).toString,array(1).toInt)
  }

  def main(args: Array[String]): Unit = {
    val unapplyTest = UnapplyTest("localhost:8080")
    println(unapplyTest.x+":" + unapplyTest.y)
    var test  = "localhost:8080"
    test match {
      case UnapplyTest("localhost",8080) => print("I am here")
    }
  }
}

test 是String类型,本身是无法匹配UnapplyTest 类型的。
应为在unapply里面定义里,
在这里会先将String,调用unapply 然后与输出的option 比较。

输出:
localhost:8080
I am here
Process finished with exit code 0










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值