1

谁能告诉我如何重写这段代码以避免多余的部分?

   val lineSplit = line.split(" ")
      lineSplit match {
        case Array(cls @ TaggedString(), prop @ TaggedString(), value @ Literal(), ".") => {processProperty(prop);processLiteral(value)}
        case Array(cls @ TaggedString(), prop @ TaggedString(), value @ LiteralwithSchema(), ".") => {processProperty(prop);processExtendedLiteral(value)}
        case Array(cls @ TaggedString(), prop @ TaggedString(), value @ TaggedString(), ".") => {processProperty(prop);processTag(value)}
        case _ => throw new IllegalArgumentException("unable to identify line format")

      }

正如您可能已经看到的那样,具有提取属性的部分总是相同的。你有什么想法如何充分考虑那部分吗?

谢谢你的输入,

斯特凡

4

2 回答 2

1

在您的情况下,我只是将匹配加倍(尽管也可以编写自定义提取器)并避免重复返回一个可以完成工作的函数:

def badLine() = throw new IllegalArgumentException("unable to identify line format")
lineSplit match {
  case Array(cls @ TaggedString(), prop @ TaggedString(), x, ".") => 
    val processValue = x match {
      case value: Literal() => () => processLiteral(value)
      case value: LiteralwithSchema() ...
      ...
      case _ => badLine()
    }
    processProperty(prop)
    processValue()
  case _ => badLine()
}
于 2013-06-24T16:09:38.700 回答
0
 val lineSplit = line.split(" ")
  lineSplit match {
    case Array(cls @ TaggedString(), prop @ TaggedString(), value @ Literal(), ".") => {processProperty(prop);processValue(value)}
    case _ => throw new IllegalArgumentException("unable to identify line format")
  }

def processValue(x: String): String = {
    x match {
      case Literal() => processLiteral(x)
      case LiteralwithSchema() => processExtendedLiteral(x)
      case TaggedString() => processTag(x)
      case _ => throw new IllegalArgumentException("value has an unknown format!")
    }

我决定将价值处理因素考虑到一种对我来说更容易的方法。现在看代码,这个问题现在感觉有点尴尬,哈哈。}

于 2013-06-25T13:42:00.107 回答