简体   繁体   English

Scala:模式匹配多个Option参数

[英]Scala: Pattern match multiple Option arguments

I would like to achieve something like the following: 我想实现以下目标:

  private def msgPrefix(implicit myClass: MyClass, anotherClass: AnotherClass) = {        
    Option(myClass, anotherClass) match {
      case Some(validMyClass, validAnotherClass) => validMyClass.process + validAnotherClass.process
      case _       => ""
    }
  }

What is the right way to do this? 什么是正确的方法?

I'm not sure I understood what you're looking for, but : 我不确定我是否了解您的要求,但是:

 private def msgPrefix(implicit myClass: MyClass, anotherClass: AnotherClass) = {        
   (Option(myClass), Option(anotherClass)) match {
     case (Some(validMyClass), Some(validAnotherClass)) => validMyClass.process + validAnotherClass.process
     case _ => ""
   }
 }

This will return the empty String if at least one of the two arguments is null, ie : 如果两个参数中的至少一个为null,则将返回空String,即:

scala> msgPrefix(MyClass("foo"),null)
res2: String = ""

scala> msgPrefix(MyClass("foo"),AnotherClass("bar"))
res3: String = foobar

But you probably should just change the type of the arguments to Option[MyClass] and Option[AnotherClass] (if you can). 但是您可能应该只将参数的类型更改为Option[MyClass]Option[AnotherClass] (如果可以)。

I agree with Marth that your arguments should probably be Option[MyClass] and Option[AnotherClass] . 我同意Marth的观点,您的论点可能应该是Option[MyClass]Option[AnotherClass] But to answer your original question, you can use a for comprehension rather than pattern matching: 但是要回答您的原始问题,您可以使用a来理解而不是模式匹配:

private def msgPrefix(implicit myClass: MyClass, anotherClass: AnotherClass) = {
  val prefix = for {
    validMyClass <- Option(myClass)
    validAnotherClass <- Option(anotherClass)
  } yield validMyClass.process + validAnotherClass.process
  prefix.getOrElse("")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM