简体   繁体   English

用于将可选字符串解析为int

[英]For comprehension parsing of optional string to int

Say I have the following for comprehension: 说我有以下几点理解:

val validatedInput = for {
    stringID <- parseToInt(optionalInputID)
} yield (stringID)

where optionalInputID is an input parameter of type Option[String] . 其中optionalInputID是类型Option[String]的输入参数。 I want to be able to convert an Option[String] into just a String, if of course there is an option present. 我希望能够将Option [String]转换为只是一个String,如果当然存在一个选项。 As far as I'm aware, you cannot case match inside a for comprehension. 据我所知,您不能在a内进行大小写匹配以进行理解。

Some details have been omitted, such as other for comprehension items. 一些细节已被省略,例如理解项目的其他细节。 Therefore I would like to know if it's possible to do this inside the for comprehension. 因此,我想知道是否有可能在理解中做到这一点。 If not, then what's a suitable alternative? 如果没有,那么什么是合适的选择? Can I do it outside of the for comprehension? 我可以在理解之外做吗?

Simply add it to the for comprehension : 只需将其添加到for comprehension

val validatedInput = for {
  inputID <- optionalInputID
  stringID <- parseToInt(inputID)
} yield (stringID)

It will work only if parseToInt has type of Option . 仅当parseToInt具有Option类型时,它才parseToInt If it returns something of Try , you can't do it - because you can't mix Try and Option in the same for-comprehension. 如果它返回了Try ,那么您将无法执行此操作-因为您无法在相同的理解中混合使用TryOption

If parseToInt returns Try , you can do the following: 如果parseToInt返回Try ,则可以执行以下操作:

val validatedInput = for {
  inputID <- optionalInputID
  stringID <- parseToInt(inputID).toOption
} yield (stringID)

I want to be able to convert an Option[String] into just a String. 我希望能够将Option [String]转换为一个字符串。

Therefore I would like to know if it's possible to do this inside the for comprehension 因此,我想知道是否有可能在理解范围内进行此操作

In Scala, for-comprehension desugars into a combinitation of map , flatMap , filter , none of which allows to extract the value out of the Option . 在Scala中, for-comprehension理解变成了mapflatMapfilter ,这些都不允许从Option提取值。

If not, then what's a suitable alternative? 如果没有,那么什么是合适的选择? Can I do it outside of the for comprehension? 我可以在理解之外做吗?

To do so you can use one of get (unsafe), or it safer version getOrElse , or fold : 为此,可以使用get (不安全)之一,或者使用更安全的getOrElsefold版本:


val validatedInput: Option[String] = Some("myString")

scala>validatedInput.get
// res1: String = "myString"

scala>validatedInput.getOrElse("empty")
// res2: String = "myString"

scala>validatedInput.fold("empty")(identity)
// res3: String = "myString"

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM