Get value from Option parameter in scala

Viewed 8914

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))
4 Answers

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

I think you can go that way:

subject.map(s => if(StringUtils.isNotBlank(s)) require(s) else s)

Options should, from a practical perspective, almost never be null in Scala (I'd argue never, but there are all sorts of compromises and exceptions, especially when working with Java dependencies where null checks are more common-place).

With some pre-processing and pattern-matching, you may find this approach acceptable:

// When working with `Option`s, naming convention usually is "[name_of_var]Opt"
case class Envelope( subjectOpt: Option[String] ) {

    // Utility to check whether or not this `Envelope` has a subject
    def hasSubject: Boolean = subjectOpt.isDefined
    
    // Get the subject or throw an exception if it does not have one (None)
    def getSubject: String = {
        subjectOpt match {
            case None => throw Exception( "Envelope has no subject!" )
            case Some( subject ) => subject
        }
    }
}
    
object Envelope {

    // Utility to create an `Envelope` with no subject
    def apply(): Envelope = Envelope(None)

    // Utility to do a bit of pre-processing, checking for `null` or empty strings
    def apply( subject: String ): Envelope = {
        if ( subject == null || subject.isEmpty ) Envelope()
        else Envelope( Some( subject ) )
    }
}

val nullString: String = null

// Example usages (will have no subject):
val envelopeWithNoSubject: Envelope = Envelope()
val envelopeWithEmptySubject: Envelope = Envelope( "" )
val envelopeWithNullSubject: Envelope = Envelope( nullString )

// envelopeWithNoSubject, ...EmptySubject, and ...NullSubject all return:
... .hasSubject // False
... .getSubject // Exception: Envelope has no subject!

// Example use with subject
val envelopeWithSubject: Envelope = Envelope( "Scala" )

envelopeWithSubject.hasSubject// True
envelopeWithSubject.getSubject // "Scala"

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.

Related