scala – 使用选项值构造Map
发布时间:2020-12-16 10:08:20 所属栏目:安全 来源:网络整理
导读:我想建立一个像这样的地图: def one = "one" def two = "two" def three = Some("three") Map[String,String]("one" - one,"two" - two,"three" - three) 这将无法编译,因为方法三返回Option而不是String. 我可以这样做: Map[String,"two" - two) ++ three
我想建立一个像这样的地图:
def one = "one" def two = "two" def three = Some("three") Map[String,String]("one" -> one,"two" -> two,"three" -> three) 这将无法编译,因为方法三返回Option而不是String. Map[String,"two" -> two) ++ three.map(t => Map("three" -> t)).getOrElse(Map.empty[String,String]) 现在它只会在列表中添加选项. 但必须有一种更优雅的方式. (例如,lift-json知道如何在构造JValue时过滤掉Options). 有什么建议? 解决方法
为了向您的客户提供一个很好的界面,您可以扩展其中一个Map以执行解包:
class MyMap[A,B](private val tuples: (A,Option[B])*) extends collection.DefaultMap[A,B] { private val container = new collection.mutable.HashMap[A,B]() container ++= tuples collect {case (k,Some(v)) => (k,v)} def iterator = container.iterator def get(id: A) = container.get(id) override def size = container.size } 将它与隐含的组合(A,B)成对(A,选项[B]): implicit def pairToPairWithSomeValue[A,B](t: (A,B)): (A,Option[B]) = (t._1,Some(t._2)) 并将其用作: def one = "one" def two = "two" def three = Some("three") def four = None val mm = new MyMap("one" -> one,"three" -> three,"four" -> four) mm foreach println /* (two,two),(one,one),(three,three) */ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |