scala学习笔记:match表达式

写了一个超级长的表达式,估计不是最简洁的:

scala> def foo(ch:Any)=ch match { case true=>"male";case false=>"female";case i:Int if(i==0)=>"female";case i:Int if(i!=0)=>"female";case str:String=>if(str!="male"&&str!="female") "?" else str;case _=>"?"}
foo: (ch: Any)java.lang.String

scala> foo("female")
res14: java.lang.String = female

scala> foo("male")
res15: java.lang.String = male

scala> foo(1)
res16: java.lang.String = female

scala> foo(0)
res17: java.lang.String = female

scala> foo(true)
res18: java.lang.String = male

scala> 

再来个case class的:

scala> case class Person(name:String){val _name=name;}
defined class Person

scala> val p1=new Person("bluejoe")
p1: Person = Person(bluejoe)

scala> p1 match {case Person(name)=> name}
res24: String = bluejoe

你可能感兴趣的:(scala学习笔记:match表达式)