scala模式匹配和异常处理

scala异常处理:

1, try -catch- finally

object TryTest {
  def main(args: Array[String]): Unit = {

    try {
      val choice = args(0)
      val choiceVal = choice.toInt
      
      if (choiceVal == 1) {
        println("----a ")
      }
      else if (choiceVal == 2) {
        println("----b ")
      }
      else {
        println("----sorry, no matched choice... ")
      }
    } catch {
      case e:Exception => println("err...",e.getMessage)
    } finally {
      println("finally, clean up....")
    }
  }//main
}

2,模式匹配

  • 1, 模式匹配的概念
object MatchTest {
  def main(args: Array[String]): Unit = {
    val choice=args(0)//1

    val res=choice match {
      case "1"=>"a"
      case "2"=>"b"
      case _=>"null"
    }

    println(res)//a
  }
}
  • 2, 模式匹配的实际应用: 
    spark 读取hbase数据,取出某个字段的值,求和计算
val rdd = sc.newAPIHadoopRDD(
      hbaseConf,
      classOf[TableInputFormat],
      classOf[ImmutableBytesWritable],
      classOf[Result]
)
val rdd2= rdd.map(_._2).map(result => {
      val cost = Bytes.toString(result.getValue(Bytes.toBytes("f"), Bytes.toBytes("cost")))

      val costValue = cost match {
        case null => 0
        case "" => 0
        case _ => cost.toString.toLong
      }
      costValue
})

val arr = rdd2.collect()
val totalCost = arr.sum
println("cost求和统计: "+totalCost)

综上所述, 模式匹配用来做异常处理,是一个优雅的选择!

你可能感兴趣的:(编程语言-scala)