Option(value) 和 Some(value) 的区别 [英] Difference between Option(value) and Some(value)

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

问题描述

我是 Scala 的新手!

I am new to scala !

我的问题是,是否有包含成员的案例类

My question is, if there is case class that contains a member

myItem:Option[String]

当我构造类时,我需要将字符串内容包装在:

When i construct the class, i need to wrap the string content in:

Option("some string")

Some("some string")

有什么不同吗?

谢谢!

推荐答案

如果你查看 Scala 的源代码 你会注意到 Option(x) 只计算 x 并返回 Some(x) 在非空输入上,Nonenull 输入上.

If you look into Scala's sources you'll notice that Option(x) just evaluates x and returns Some(x) on not-null input, and None on null input.

当我不确定 x 是否可以为 null 时,我会使用 Option(x)Some(x) 当 100% 确定 x 不是 null 时.

I'd use Option(x) when I'm not sure whether x can be null or not, and Some(x) when 100% sure x is not null.

要考虑的另一件事是,当您想创建一个可选值时,Some(x) 会生成更多代码,因为您必须明确指出该值的类型:

One more thing to consider is when you want to create an optional value, Some(x) produces more code because you have to explicitly point the value's type:

val x: Option[String] = Some("asdasd")
//val x = Option("asdasd") // this is the same and shorter

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

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