Home > Software engineering >  Scala overload constructor with mutable List of different type
Scala overload constructor with mutable List of different type

Time:05-09

I am trying to overload a constructor with mutable list of Int and Long , it mentions that the method is already defined. I need updateList to be either mutable.MutableList[Int] or mutable.MutableList[Long]

object PercentileDistribution {
  def apply(updateList: mutable.MutableList[Int], percentileDistribution: PercentileDistribution): PercentileDistribution = {
    updateList.foreach { x =>
      percentileDistribution.update(x)
    }
    percentileDistribution
  }

  def apply(updateList: mutable.MutableList[Long], percentileDistribution: PercentileDistribution): PercentileDistribution = {
    updateList.foreach { x =>
      percentileDistribution.update(x)
    }
    percentileDistribution
  }
}

Being new to scala I am facing some issues, any help is appreciated.

CodePudding user response:

The error clearly refers to the upcasting that is happening in your code. An Int can be represented as a Long hence you have essentially written the same method with one methods parameter being the upcasted version of the parameter of the other apply method.

You can simply use the apply method that has the MutableList[Long] type and remove the one with Int.

Follow this documentation from the official scala docs and you will get a good idea as to how types behave in Scala

  • Related