scala的option使用实例

下面是option的一个小练习,直接上代码:

import scala.collection.mutable.ArrayBuffer
object OptionTest {
  def main(args: Array[String]) {
      val tmp1 = Option(Array(1,2))
      val tmp2 = Option(None)

      case class Info(name:String,age:Long)
      val tmp3 = ArrayBuffer[Option[Info]]()
      tmp3 += None
      tmp3 += Some(Info("abc",18))
      tmp3 += None
      tmp3 += Some(Info("efg",60))
      tmp3.toArray.foreach(item=>println(item.isDefined,if(item.isDefined) "name=%s:age=%s".format(item.get.name,item.get.age) else "本对象为None"))

  }

}
运行结果为:


猜你喜欢

转载自blog.csdn.net/wjj547670933/article/details/51501791