从scala中的Option参数获取值

im9ewurl  于 2022-12-13  发布在  Scala
关注(0)|答案(4)|浏览(221)

我有一个参数

case class Envelope(subject: Option[String]) {
}

且我希望仅在subject为非空时应用required函数。
大致如下:

require(StringUtils.isNotBlank(subject))
d5vmydt9

d5vmydt91#

您还可以尝试以下操作:

case class Envelope(subject: Option[String])

def check(en: Envelope): Boolean = {
    require(en.subject.isDefined)
    true
    }

它会更好,你没有任何需要导入StringUtils
要从Option中获取值,您应该使用getorElse。在这里,我们可以定义变量的默认值。例如:

def check(str: Option[String]): String = {
  str.getOrElse("")
 }

scala> check(None)
res1: String = ""

scala> check(Some("Test"))
res2: String = Test

只有get会在取得None时掷回例外状况。例如:

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
7eumitmz

7eumitmz2#

我想你可以走那条路:
subject.map(s => if(StringUtils.isNotBlank(s)) require(s) else s)

d8tt03nd

d8tt03nd3#

从实际的Angular 来看,Option在Scala中几乎不应该为null(我认为***永远不应该***,但是有各种各样的妥协和例外,特别是在处理null检查更常见的Java依赖关系时)。
通过一些预处理和模式匹配,您可能会发现这种方法是可以接受的:

// 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"
aiazj4mn

aiazj4mn4#

您应该将require函数调用更改为

require(StringUtils.isBlank(subject.get))

.get方法会传回subjectOption所携带的字串。

相关问题