在 Scala 中使用 Some() 和 Option() [英] Working with Some() and Option() in Scala

查看:77
本文介绍了在 Scala 中使用 Some() 和 Option()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在与在 Scala 中解析 JSON 字符串的函数式方法的概念作斗争,并在返回 Option(something) 的情况下陷入困境.我提出了这个问题,有用的答案源源不断.

I've been fighting with the concept of the functional way of parsing a JSON string in Scala and ran flat into the wall with Option(something) being returned. I popped the questionand the helpful answers came streaming in.

问题是,作为 Scala 的新手,正确的方法是什么?

The problem is, as someone being pretty new to Scala, what is the correct way?

目前我正在这样做:

import util.parsing.json.JSON._

object JsonSoap {
  def main(args: Array[String]) {
    val x = parseFull("""{"name":"Joe","surname":"SOAP"}""")

    val y = x collect {
      case m: Map[_, _] => m collect {
        case (key: String, value: String) => key -> value
      }
    }

    val z = for (m <- y; name <- m.get("name"); surname <- m.get("surname"))
    yield {
      <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        <soap:Body>
          <Person>
            <Name>{name}</Name>
            <Surname>{surname}</Surname>
          </Person>
        </soap:Body>
      </soap:Envelope>
    }

    println(z)
  }
}

我仍然坚持使用 Some()

I'm still stuck with Some()

有什么好的模式可以解决我的问题吗?当然,这必须是经过充分探索的领域.如何改进我的代码?

Is there a nice pattern to solving my problem? Surely this has to be well explored territory. How can I improve my code?

推荐答案

你没有卡住"使用Some - 您拥有优势,因为您拥有Some!在 Java 中,您将被困在一个类型未表达它可能实际上不存在的事实的值中!

You are not "stuck" with Some - you have the advantage that you have a Some! In Java, you would be stuck with a value whose type did not express the fact that it might not actually exist!

MyThing recklessly = apiCall.getMeAThing();
recklessly.iSureHopeImNotNull();  //OH NOES!

对比一下

apiCall.getMeAThing foreach (_.cannotPossiblyBeNull)

Option 数据类型意味着可能不存在";您的查询的一部分实际上已融入查询的返回类型中.请坚持使用 Option - 几个星期后,当您编写 Java 代码时,您将脱光头发,而它不存在!

The Option datatype means that the "might not exist" bit of your query is actually baked into the return type of the query. Please stick with Option - in a few weeks you will be pulling out your hair when you go to write Java code and it's not there!

你可能会说:

噢,但我需要把我拥有的值加1

Aw, but I need to take the value I have and add 1 to it

我说:

apiCall.getMeAThing map (_ + 1)

你可能会说

噢,但我需要将它传递给一个方法,如果我有 null,则默认为空字符串

Aw, but I need to pass it to a method, defaulting to the empty String if I have null

我说:

foo( apiCall.getMeAThing getOrElse "" )

你可能会说

哦,但我使用该值来调用另一个 API 方法并获取其他内容

Aw, but I use that value to call another API method and get something else

我说:

apiCall.getMeAThing flatMap apiCall.getMeAnotherThing

你肯定会说

哦,但是对于所有这些对象创建来说效率非常低

Aw but that's awfully inefficient with all those object creations

我说:试试看,会好的"

I say: "try it, it will be just fine"

这篇关于在 Scala 中使用 Some() 和 Option()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆