2

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?

2 Answers 2

3

With

def this(dt: Seq[Double]) = this(dt.zipWithIndex.map(_.swap).toMap)
  • You're creating a new map Map[Int,Double]; Int being the type of the index created by zipWithIndex.

  • If T were Int, 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 T to Int at 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 <: Int could resolve your problem; however it seems a bit unlikely that T is a subclass of Int...

  • If it is always true that T : Int, then drop the generic T.

  • If T is to remain generic and unbounded then that leaves you with making a special case for when T : Int; senia's solution looks good for that.

Sign up to request clarification or add additional context in comments.

Comments

0

You can fix it with companion object:

scala> :paste
// Entering paste mode (ctrl-D to finish)

class V[T](m: Map[T,Double])

object V{
  def apply(dt: Seq[Double]) = new V[Int](dt.zipWithIndex.map(_.swap)(collection.breakOut))
}

// Exiting paste mode, now interpreting.

defined class V
defined module V

scala> V(Seq(1.,2.,3.))
res0: V[Int] = V@1130e2ea

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.