0

I have an Option[String] and I want to make sure that the string is lower case. What is the idiomatic way to 'reach into' the Option and make the transformation without having to extract the string and then put it back into an Option?

Thanks

Zuriar
  • 11,096
  • 20
  • 57
  • 92
  • You can `map`, there are a lot of examples around about mapping options. – Ende Neu Jan 15 '15 at 15:27
  • 5
    I don't know why they called it `map` instead of `reachInto`. – som-snytt Jan 15 '15 at 19:34
  • 1
    so what is wrong with my question that warrants people to down vote it? Sorry we are not all born geniuses. – Zuriar Jan 15 '15 at 23:35
  • I agree. I think people forget that they didn't always know this stuff. You'll definitely want to do some research. FYI, `Option` is an *applicative functor*, which is basically a fancy way of saying it has a `map` method that modify the data it contains, even converting it to a different type. – acjay Jan 16 '15 at 05:37
  • 1
    @acjay That's just a functor, without the "applicative" part. – Alexey Romanov Jan 16 '15 at 21:24
  • @AlexeyRomanov For my own enlightenment and others', could you explain the difference? – acjay Jan 19 '15 at 02:02
  • 1
    @acjay See e.g. http://eed3si9n.com/learning-scalaz/Applicative.html or http://stackoverflow.com/a/19882450/9204. – Alexey Romanov Jan 19 '15 at 07:04

2 Answers2

6

Just call map on it:

stringOpt.map(_.toLowerCase)
drexin
  • 24,225
  • 4
  • 67
  • 81
3
val x : Option[String] = Some("Hello")
x map (_.toLowerCase)
res2: Option[String] = Some(hello)
Chris Stewart
  • 1,641
  • 2
  • 28
  • 60
  • Thanks! So simple, however that takes all letters to lowercase and I need the first letter in the sentence to remain Upper case... – Zuriar Jan 15 '15 at 15:32
  • Look for an additional method inside of the StringOps library which is here http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.StringOps – Chris Stewart Jan 15 '15 at 15:33