scala 如何在选项 [String] 中设置字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11708298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set a String in a Option[String]?
提问by i.am.michiel
When I'm trying to affect a value of type String in a field of type Option[String] I get the following error :
当我尝试影响 Option[String] 类型字段中的 String 类型值时,出现以下错误:
type mismatch; found : String required: Option[String]
How can I affect value myValue:Stringinto field myField:Option[String]?
如何将值影响myValue:String到字段中myField:Option[String]?
回答by Channing Walton
You can also just use Option(myValue)which will convert null to Noneand non-null to Some.
您也可以使用Option(myValue)which 将 null 转换为None和非 null转换为Some。
回答by Kim Stebel
You can wrap any object in an Optionlike this:
您可以Option像这样包装任何对象:
val opt = Some("foo")
回答by FUD
You can just wrap your object in Some class
您可以将对象包装在 Some class 中
val myField = Some(myValue)
Or if you dont have Anything, pass
或者如果你没有任何东西,通过
None
Its called Option pattern
它称为选项模式
回答by Roman Kazanovskyi
If you want to convert empty string to None more universal solution is: Option(str).filter(_.nonEmpty)
如果要将空字符串转换为 None 更通用的解决方案是: Option(str).filter(_.nonEmpty)

