加载中...

Tuple/case class/模式匹配


Tuple为编程提供许多便利

  • 函数可以通过tuple返回多个值
  • tuple可以存储在容器类中,代替java bean
  • 可以一次为多个变量赋值

使用tuple的例子

  1. val (one, two) = (1, 2)
  2. one //res0: Int = 1
  3. two //res1: Int = 2
  4. def sellerAndItemId(orderId: Int): (Int, Int) =
  5. orderId match {
  6. case 0 => (1, 2)
  7. }
  8. val (sellerId, itemId) = sellerAndItemId(0)
  9. sellerId // sellerId: Int = 1
  10. itemId // itemId: Int = 2
  11. val sellerItem = sellerAndItemId(0)
  12. sellerItem._1 //res4: Int = 1
  13. sellerItem._2 //res5: Int = 2

用模式匹配增加tuple可读性

  1. val sampleList = List((1, 2, 3), (4, 5, 6), (7, 8, 9))
  2. sampleList.map(x => s"${x._1}_${x._2}_${x._3}")
  3. //res0: List[String] = List(1_2_3, 4_5_6, 7_8_9)
  4. sampleList.map {
  5. case (orderId, shopId, itemId) =>
  6. s"${orderId}_${shopId}_$itemId"
  7. }
  8. //res1: List[String] = List(1_2_3, 4_5_6, 7_8_9)

上下两个map做了同样的事情,但下一个map为tuple中的三个值都给了名字,增加了代码的可读性.

match和java和switch很像,但有区别

  1. match是表达式,会返回值
  2. match不需要”break”
  3. 如果没有任何符合要求的case,match会抛异常,因为是表达式
  4. match可以匹配任何东西,switch只能匹配数字或字符串常量
  1. //case如果是常量,就在值相等时匹配.
  2. //如果是变量,就匹配任何值.
  3. def describe(x: Any) = x match {
  4. case 5 => "five"
  5. case true => "truth"
  6. case "hello" => "hi!"
  7. case Nil => "the empty list"
  8. case somethingElse => "something else " + somethingElse
  9. }

case class,tuple以及列表都可以在匹配的同时捕获内部的内容.

  1. case class Sample(a:String,b:String,c:String,d:String,e:String)
  2. def showContent(x: Any) =
  3. x match {
  4. case Sample(a,b,c,d,e) =>
  5. s"Sample $a.$b.$c.$d.$e"
  6. case (a,b,c,d,e) =>
  7. s"tuple $a,$b,$c,$d,$e"
  8. case head::second::rest =>
  9. s"list head:$head second:$second rest:$rest"
  10. }

Case class

  1. 模式匹配过程中其实调用了类的unapply方法
  2. Case class 是为模式匹配(以及其他一些方面)提供了特别的便利的类
  3. Case class 还是普通的class,但是它自动为你实现了apply,unapply,toString等方法
  4. 其实tuple就是泛型的case class

还没有评论.