Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Int convert to Double when unnecessary #9935

Open
scabug opened this issue Sep 22, 2016 · 3 comments
Open

Int convert to Double when unnecessary #9935

scabug opened this issue Sep 22, 2016 · 3 comments

Comments

@scabug
Copy link

scabug commented Sep 22, 2016

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
Copy link
Author

scabug commented Sep 22, 2016

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
Copy link
Author

scabug commented Sep 22, 2016

@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
Copy link
Author

scabug commented Sep 22, 2016

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants