scala unapply的测试

来源:互联网 发布:cocos2dx mac 编辑:程序博客网 时间:2024/06/10 16:00
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 1h:aabc 111 1 f:aabc g:111 1

可见这与if所说的一致。

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

0 0
原创粉丝点击