'Get value from Option parameter in scala
I have a parameter
case class Envelope(subject: Option[String]) {
}
and I want to apply a require function only if subject is non null.
Something like below:
require(StringUtils.isNotBlank(subject))
Solution 1:[1]
You should be changing the require function call to the following
require(StringUtils.isBlank(subject.get))
.get method returns the string that the subject Option carries.
Solution 2:[2]
You can try this also:
case class Envelope(subject: Option[String])
def check(en: Envelope): Boolean = {
require(en.subject.isDefined)
true
}
It will be finer and you don't have any need to import StringUtils.
For fetching the value from Option you should go for the getorElse. Here we can define the default value for the variable. Ex:
def check(str: Option[String]): String = {
str.getOrElse("")
}
scala> check(None)
res1: String = ""
scala> check(Some("Test"))
res2: String = Test
Only get will throw the exception when it will get None. Ex:
def check(str: Option[String]): String = {
str.get
}
scala> check(Some("Test"))
res2: String = Test
scala> check(None)
java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:347)
at scala.None$.get(Option.scala:345)
at check(<console>:24)
... 48 elided
Solution 3:[3]
I think you can go that way:
subject.map(s => if(StringUtils.isNotBlank(s)) require(s) else s)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ramesh Maharjan |
| Solution 2 | |
| Solution 3 | perbellinio |
