Scala断言

断言:提供了一组断言函数以用作在代码中记录和动态检查不变量的方式。

import scala.Predef._

def addNaturals(nats: List[Int]): Int = {
    // assert(nats forall (_ >= 0), "List contains negative numbers")
    require(nats forall (_ >= 0), "List contains negative numbers")
    nats.foldLeft(0)(_ + _)
          } ensuring (_ >= 0) // 这里的"_"是函数的返回值

scala> addNaturals(List(-1, -2, 2, 3))
java.lang.IllegalArgumentException: requirement failed: List contains negative numbers
  at scala.Predef$.require(Predef.scala:224)
  at addNaturals(<console>:50)
  ... 56 elided

  
scala> addNaturals(List(1, 2, 3, 4, 10))
res15: Int = 20

 

posted @ 2017-01-11 16:59  智能先行者  阅读(1183)  评论(0编辑  收藏  举报