1

我有一个带有两个输入的 simpleNode 类,你只能填充其中一个,它们都是 Scala 中的 Map 但我必须检查地图中的数据类型才能填充任何输入

我为此编写的代码是:

class SimpleNode (
  val uriTriples: collection.mutable.Map[String, List[String]] = collection.mutable.Map.empty,
  val valueTriples: collection.mutable.Map[String, Map[String,String]] = collection.mutable.Map.empty
                ) 
  {              
    def this(map:collection.mutable.Map) = {
      map.values.head match {
      case uri : List[String] => this(uris,null) 
      case values : Map[String,String] => this(null,values)
      case _=>
    }
  }
}

我总是面临错误:

a:34: error: 'this' expected but identifier found.
[INFO]        map.values.head match {
[INFO]        ^                       
4

1 回答 1

3

常用的消歧策略:

class SimpleNode (
  val uriTriples: collection.mutable.Map[String, List[String]] = collection.mutable.Map.empty,
  val valueTriples: collection.mutable.Map[String, Map[String,String]] = collection.mutable.Map.empty
)
  {
    def this(map:mutable.Map[String, List[String]]) = this(map, null)
    def this(map:mutable.Map[String, Map[String,String]])(implicit d: DummyImplicit) = this(null, map)
}

或者工厂更步行:

object SimpleNode {
  def apply(...) = ???
}
于 2013-08-20T18:24:19.940 回答