2013-08-20 44 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我以爲你的意思是不推薦。 –