scala unapply的测试

object Name {def unapply(ipt:String)={val pos = ipt.indexOf(" ")
    if (pos == -1) None 
    else Some((ipt.substring(0,pos),ipt.substring(pos+1)))
  }
}
object IsCompound{def unapply(ipt:String)=ipt.contains(" ")}
val author = "aabc 111 1"
println(IsCompound.unapply(author))
author match{case Name(f,uu IsCompound())=>println("haha")}
author match{case Name(f,uu IsCompound(t))=>println("haha")}
author match{case Name(f,IsCompound(t))=>println("haha")}
author match{case Name(f,uu@IsCompound(t))=>println("haha")}
author match{case Name(f,uu@IsCompound())=>println("haha")}
/* if:uu IsCompound() : unapply receive uu; so it's a wrong syntax in the case of IsCompound has a boolean unapply 
 * if: uu IsCompound(t) : equals IsCompound(uu,t);so it's a wrong syntax in the case of IsCompound has a boolean unapply 
 * if: IsCompound(t) : equals uu IsCompound();so this it's a wrong syntax in the case of IsCompound has a boolean unapply 
 * if: uu@IsCompound(t) : unapply receive uu and t is set the return value of unapply;so it's a wrong syntax in the case of IsCompound has a boolean unapply
 * if: uu@IsCompound():unapply receive uu;
 */

 
 
 

五个if写明了所有的情况,代码可直接测试,测试时请对照if中的说明;

这里的unapply指的是IsCompoundunapply,

可以对它修改以不报错,但是原理就是这样的.更具体的解释如下:

val author1 = "aabc 111 1"
  val a Name()=author1
  println("a:"+a)
  val Name(b)=author1
  println("b:"+b)
  val c Name(d)=author1
  println("c:"+c+" "+"d:"+d)
  val h @Name(f,g)=author1
  println("h:"+h+" "+"f:"+f+" "+"g:"+g)
输出如下:
a:(aabc,111 1)
b:(aabc,111 1)
c:aabc d:111 1
h:aabc 111 1 f:aabc g:111 1

可见这与if所说的一致。

有问题请留言,或者发送邮件到:zhanghao_study@163.com.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值