简体   繁体   English

如何访问返回 Option 对象的方法?

[英]How can I access a method which return Option object?

I have to call method which returns Option[List[Obj]] .我必须调用返回Option[List[Obj]]

After I call I need to iterate the List and print the Obj attributes.调用后,我需要迭代 List 并打印 Obj 属性。

object Tester{
  def main(args:Array[String]) {
    val ymlFilename ="some.yml";
  val entities: Option[QueryEntities] =  InputYamlProcessor.process(ymlFilename)

        for( e: QueryEntities  <- entities ){
          /// this is not working
           //How to access the columnFamily, fromData and toDate ?
        }
  }

Complete sample完整样品

https://gist.github.com/shatestest/fdeaba767d78e171bb6c08b359fbd1bf https://gist.github.com/shatestest/fdeaba767d78e171bb6c08b359fbd1bf

The most iconic way ot do it is to unwrap values with scala is to use pattern matching to unwrap the value.最有代表性的方法是使用 Scala 解包值,即使用模式匹配来解包值。

entities match {
    case Some(queryEntities: QueryEntities) => 
      queryEntities.entities.foreach { case e =>
        println(e.columnFamily)
        println(e.fromDate.getOrElse("defaultFromDateHere")
        println(e.toDate.getOrElse("defaultToDateHere"))
      }
    case None => println("No value")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何模拟没有返回值的方法是Option [SomeCaseClassDefinedInsideThisClass]的方法的返回 - How to mock return of None of method which return type is Option[SomeCaseClassDefinedInsideThisClass] Scala:如何返回镶木地板文件的选项[Dataframe](位于adls中)-不使用spark / sql会话 - Scala: How can I return Option[Dataframe] of parquet file(which is in adls) - without using spark/sql session 如何声明在Thrift / Scrooge中返回Option值的方法? - How can I declare a method which returns an Option value in Thrift/Scrooge? 如何提供编译时保证我的方法将返回它在Scala中获取的相同对象? - How can I provide a compile-time guarantee that my method will return the same object it gets in Scala? 我可以喷雾返回Future [Option [Foo]]吗? - Can I return Future[Option[Foo]] in spray? 如何测试使用specs2调用error()的方法? - How can I test a method which calls error() with specs2? 如何使用依赖返回类型覆盖方法? - How can I override a method with a dependent return type? 如何从方法返回通用类? - How can I return a generic class from a method? 如何在Lift中访问代码段选项? - How Do I Access A Snippet Option In Lift? 我如何像一个类实例一样返回一个scala“对象”? - How can I return a scala “object” as if it's a class instance?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM