2013-08-20 17 views
1

我有一个simpleNode类,有两个输入,你只能填充其中的一个,它们都是Scala中的Map,但我必须检查映射中的数据类型以填充任何的输入基于scala条件的重载构造函数

我写这样做的代码是:

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]  ^      
+1

http://stackoverflow.com/questions/1095329/scala-constructor-overload – Brian

+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(...) = ??? 
} 
+0

是不是在scala复制的dummyimplicit? –

+0

@HadyElsahar不是我有限的知识。 http://www.scala-lang.org/api/current/index.html#scala.Predef$$DummyImplicit –

+0

@HadyElsahar我以为你的意思是不推荐。 –