I’m trying to overload a constructor in a generic scala class but it’s not compiling.
Here’s my code:
class V[T](m: Map[T,Double]) {
def this(dt: Seq[Double]) = this(dt.zipWithIndex.map(_.swap).toMap)
}
And the error messages I get:
ERROR: called constructor's definition must precede calling constructor's definition : line 6
ERROR: overloaded method constructor V with alternatives:
(dt: Seq[Double])V[T] <and> (m: Map[T,Double])V[T] cannot be applied to
(scala.collection.immutable.Map[Int,Double]) : line 6
As far as I understand constructor overloading in scala, I think I’m following the proper syntax and the restriction that the call to this should precede everything else.
So what am I doing wrong and how can I fix this?
With
You’re creating a new map
Map[Int,Double];Intbeing the type of the index created byzipWithIndex.If
TwereInt, then you can use the constructor(m:Map[T,Double].However: T is not yet bound to a type since you’re defining the class. Nor will the type matching bind
TtoIntat this point.Therefore the type matching fails.
Solutions:
How to fix it depends on what you’re trying to do.
If it were the case that
T <: Int, then bounding the type-param with<: Intcould resolve your problem; however it seems a bit unlikely thatTis a subclass ofInt…If it is always true that
T : Int, then drop the genericT.If
Tis to remain generic and unbounded then that leaves you with making a special case for whenT : Int; senia’s solution looks good for that.