scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
232 stars 21 forks source link

Unsafe cast in StrictOptimisedMapOps.+ in 2.13 #12699

Closed retronym closed 1 year ago

retronym commented 1 year ago

Reproduction steps

Scala version: 2.13.x


object MapTest {
  def main(args: Array[String]): Unit = {
    val m1: collection.immutable.HashMap[Int, Int] = HashMap(1 -> 1);
    // class scala.collection.immutable.$colon$colon cannot be cast to class scala.collection.immutable.Map (scala.collection.immutable.$colon$colon and scala.collection.immutable.Map are in unnamed module of loader 'app')
    //  at demo.MapTest$.main(Test.scala:68)
    //  at demo.MapTest.main(Test.scala)
    //
    // This is s "delayed" CCE from the asInstanceOf that is compiled to a no-op in StrictOptimizedMapOps.+
    //
    //   @deprecated("Use ++ with an explicit collection argument instead of + with varargs", "2.13.0")
    //  override def + [V1 >: V](elem1: (K, V1), elem2: (K, V1), elems: (K, V1)*): CC[K, V1] = {
    //    val m = ((this + elem1).asInstanceOf[Map[K, V]] + elem2).asInstanceOf[CC[K, V1]]
    //    if(elems.isEmpty) m else m.concat(elems).asInstanceOf[CC[K, V1]]
    //
    val m2: Map[Int, Any] = m1.+(elem1 = 4 -> 4, elem2 = 5 -> 5, elems = List(6 -> 6, 7 -> 7, 8 -> 8, 9 -> 9): _*)
    val m3: Map[Int, Any] = m1 + (4 -> 4, 5 -> 5, 6 -> 6, 7 -> 7, 8 -> 8, 9 -> 9)
  }
}

Problem

Need to use m.mapFactory.newBuilder to get the suitable return type.