// 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"
4条答案
按热度按时间d5vmydt91#
您还可以尝试以下操作:
它会更好,你没有任何需要导入
StringUtils
。要从
Option
中获取值,您应该使用getorElse
。在这里,我们可以定义变量的默认值。例如:只有
get
会在取得None
时掷回例外状况。例如:7eumitmz2#
我想你可以走那条路:
subject.map(s => if(StringUtils.isNotBlank(s)) require(s) else s)
d8tt03nd3#
从实际的Angular 来看,
Option
在Scala中几乎不应该为null(我认为***永远不应该***,但是有各种各样的妥协和例外,特别是在处理null
检查更常见的Java依赖关系时)。通过一些预处理和模式匹配,您可能会发现这种方法是可以接受的:
aiazj4mn4#
您应该将require函数调用更改为
.get
方法会传回subject
Option
所携带的字串。