0

有没有更简洁的方式在scala中写这个?

def myFunction(somethingA: String, somethingB: Option[String]): Unit =
  if (somethingB.isDefined) 
    foo("somethingA" -> somethingA, "somethingB" -> somethingB.get) 
  else
    foo("somethingA" -> somethingA)

我在想一些事情:

def myFunction(somethingA: String, somethingB: Option[String]): Unit =
  foo("somethingA" -> somethingA, somethingB.map("somethingB" -> _).getOrElse(.... pleh ....))

但是,即使我用某种表达式替换“.... pleh ....”部分,如果未定义 somethingB,我也不希望它添加映射。所以我不认为远程工作。不确定正确的解决方案是什么。

4

4 回答 4

2

不太干净:

def myFunction(somethingA: String, somethingB: Option[String]): Unit = somethingB match {
  case Some(b) => foo("somethingA" -> somethingA, "somethingB" -> b)
  case None    => foo("somethingA" -> somethingA)
}
于 2013-06-25T23:52:21.977 回答
2

你不说是什么foo,而是给定

scala> def foo(ps: (String, String)*) = ps.size
foo: (ps: (String, String)*)Int

然后

scala> def myFunction(somethingA: String, somethingB: Option[String]): Int =
     | foo(List(Some("A"->somethingA), somethingB.map("B"->_)).flatten: _*)
myFunction: (somethingA: String, somethingB: Option[String])Int

可能是你想要的。

于 2013-06-26T01:22:00.623 回答
1

Option如果您使用的是 Scala 2.10,您也可以尝试折叠:

val result = somethingB.fold(foo("somethingA" -> somethingA))(b => foo("somethingA" -> somethingA, "somethingB" -> b))
于 2013-06-26T00:21:16.460 回答
0

我的 2 美分:

val a = "somethingA" -> somethingA

somethingB.map{ b =>
   foo(a, "somethingB" -> b) 
}.getOrElse { foo(a) }

几乎没有更多的可读性。顺便提一句。我认为您不能根据值更改调用绑定:(

于 2013-06-26T00:05:57.910 回答