scala / bug

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

Int convert to Double when unnecessary #9935

Open scabug opened 7 years ago

scabug commented 7 years ago

The second result type should be Int

def f1(l: Array[Int]): Array[Any] =
      l.map{ x =>
        x match {
        case x if x == 1 => x.toString
        case x if x == 2 => x.toInt
        case _ => x.toDouble
      }    
   } 

f1(Array(1,2,3)).foreach(v => println(s"$v :${v.getClass}"))
1 :class java.lang.String
2.0 :class java.lang.Double
3.0 :class java.lang.Double
scabug commented 7 years ago

Imported From: https://issues.scala-lang.org/browse/SI-9935?orig=1 Reporter: Xuefeng Wu (wuxuefeng) Affected Versions: 2.11.8, 2.12.0-RC1

scabug commented 7 years ago

@SethTisue said: Note that the following behavior is correct:

scala> Array(true, false) map { case true => 1; case false => 2.0 }
res7: Array[Double] = Array(1.0, 2.0)

because of the weak-least-upper-bound rule in SLS 8.4.

Regardless, the behavior in your example does seem incorrect to me. Looks like a bug in weak-least-upper-bound handling in the pattern matcher. The weak-least-upper-bound of Int, Double, and String is Any; I don't see anything in the spec that would permit the weak-least-upper-bound of only a subset of the clauses to influence the results.

Note that the behavior is sensitive to the ordering of clauses in the match, so for example you get different results if String comes last:

  l.map{
    case x if x == 1 => x.toInt
    case x if x == 2 => x.toDouble
    case x => x.toString
  }

1 :class java.lang.Integer
2.0 :class java.lang.Double
3 :class java.lang.String
scabug commented 7 years ago

@SethTisue said: Dotty doesn't have the bug.