Hady Elsahar
Hady Elsahar

Reputation: 2151

overloading constructor based on condition in scala

i've a simpleNode class with two inputs that u can only fill one of them which are both Map in Scala but i have to check to the type of data in maps in order to fill any of the inputs

the code i've written to do so is:

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 _=>
    }
  }
}

I always face the error :

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

Upvotes: 1

Views: 403

Answers (1)

som-snytt
som-snytt

Reputation: 39577

Usual strategy for disambiguation:

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)
}

Or a factory is more pedestrian:

object SimpleNode {
  def apply(...) = ???
}

Upvotes: 3

Related Questions