【问题标题】:How to add a XML node for Some case in pattern matching?如何在模式匹配中为某些情况添加 XML 节点?
【发布时间】:2015-02-02 16:43:38
【问题描述】:

我希望节点 test1、test2 和 test3 仅在定义 option 时出现。 下面的代码有效,但是,我不喜欢 test1,因为它不使用模式匹配(所以我需要调用 option.get);我不喜欢 test2,因为我有一条无用的行 case _ =>。而且我不喜欢 test3,因为我有等效的 .getOrElse(())。有没有很好的方法来实现这一点?

val option: Option[Int] = None

val node =
  <test>
    { if (option.isDefined) <test1>{option.get}</test1> }

    { option match {
        case Some(x) => <test2>{x}</test2>
        case _ =>
    }}

    { option.map(x => <test3>{x}</test3>).getOrElse(()) }
  </test>

【问题讨论】:

    标签: xml scala


    【解决方案1】:

    怎么样

    val node = <test> { option.iterator.map(x => <test1>x</test1>) } </test>
    

    如果您将Option 转换为Iterator,那么我认为您会通过本机XML 处理获得您正在寻找的语义(也应该与toList 和其他人一起使用)。

    【讨论】:

      【解决方案2】:

      您似乎只关心Some 大小写而忽略None

      def f(o: Option[Int]): scala.xml.Elem =
        <test>
        {
          o match {
            case Some(x) => <test1>{x}</test1><test2>{x}</test2><test3>{x}</test3>
            case None => xml.NodeSeq.Empty
          }
        }
        </test>
      

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 2021-08-12
        • 1970-01-01
        • 2017-10-05
        • 2015-12-24
        • 2023-04-05
        • 2011-09-26
        • 1970-01-01
        • 2012-03-22
        相关资源
        最近更新 更多