0

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]. I want to be able to convert an Option[String] into just a String, if of course there is an option present. As far as I'm aware, you cannot case match inside a for comprehension.

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Chris
  • 785
  • 10
  • 24

2 Answers2

4

Simply add it to the for comprehension:

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

It will work only if parseToInt has type of Option. If it returns something of Try, you can't do it - because you can't mix Try and Option in the same for-comprehension.

If parseToInt returns Try, you can do the following:

val validatedInput = for {
  inputID <- optionalInputID
  stringID <- parseToInt(inputID).toOption
} yield (stringID)
Gal Naor
  • 2,397
  • 14
  • 17
  • I get a type mismatch error. Could that be because of the possibility that there is a Some or None case? – Chris Jun 20 '19 at 15:11
  • I updated my answer, what is the return type of `parseToInt`? – Gal Naor Jun 20 '19 at 15:14
  • `Expression of type Option[(ID, int, String)] doesn't conform to the expected type Either[A1_, B1_]` The `ID` and `int` being the other statements in the for comprehension (that I want to omit the details of for this question). – Chris Jun 20 '19 at 15:15
  • I understand if this is entirely unhelpful. I'll try and update my question to accommodate this error that I just commented. – Chris Jun 20 '19 at 15:15
1

I want to be able to convert an Option[String] into just a 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.

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:


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"

Community
  • 1
  • 1
Valy Dia
  • 2,781
  • 2
  • 12
  • 32
  • Adding getOrElse to my statement seems to have worked. `stringID <- idFromString(inputID.getOrElse(""))`. Also, I have changed my statement. I do not need an int. I need an ID. But that seems to work. Thanks! – Chris Jun 20 '19 at 15:18