-
Notifications
You must be signed in to change notification settings - Fork 21
asInstanceOf inlining causes the difference in result #13103
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
Comments
Wrong Your |
Hi, @sjrd I quickly tried what you suggested class TestRow(values: Array[Any]) {
def get(i: Int): Any = values(i)
def getAs[T](i: Int): T = get(i).asInstanceOf[T]
}
object Main {
private def asOptBoolean1(r: TestRow, index: Int): Option[Boolean] = {
val bool = r.getAs[Boolean](index)
Option(bool)
}
private def asOptBoolean2(r: TestRow, index: Int): Option[Boolean] = {
Option(r.getAs[Boolean](index))
}
private def asOptJavaBoolean1(r: TestRow, index: Int): Option[Boolean] = {
val bool = r.getAs[java.lang.Boolean](index)
Option(bool)
}
private def asOptJavaBoolean2(r: TestRow, index: Int): Option[Boolean] = {
Option(r.getAs[java.lang.Boolean](index))
}
def main(args: Array[String]): Unit = {
val row = new TestRow(Array(null, true, false))
println(s"asOptBoolean1 at 0: ${asOptBoolean1(row, 0)}")
println(s"asOptBoolean1 at 1: ${asOptBoolean1(row, 1)}")
println()
println(s"asOptBoolean2 at 0: ${asOptBoolean2(row, 0)}")
println(s"asOptBoolean2 at 1: ${asOptBoolean2(row, 1)}")
println()
println(s"asOptJavaBoolean1 at 0: ${asOptJavaBoolean1(row, 0)}")
println(s"asOptJavaBoolean1 at 1: ${asOptJavaBoolean1(row, 1)}")
println()
println(s"asOptJavaBoolean2 at 0: ${asOptJavaBoolean2(row, 0)}")
println(s"asOptJavaBoolean2 at 1: ${asOptJavaBoolean2(row, 1)}")
}
} Produces
|
To unpack this a little bit more, But then the question is, if you've promised a Now, what if you want to prove at runtime that you have something of a type? You use def getAs[T](i: Int)(implicit tag: reflect.ClassTag[T]) = tag.unapply(get(i)) is probably what you want. |
Unboxing behavior is consistent with the definition of
|
The code below generates bytecode that makes
asOptBoolean1
andasOptBoolean2
to not produce the same result in case if null is provided.asOptBoolean1
will never return None.It produces the following output
The generated bytecode https://godbolt.org/z/sGhz9WYh9, as you can see there is boxing/unboxing in
asOptBoolean1
that causes null to become false as primitiveI use Scala 2.13.15
The text was updated successfully, but these errors were encountered: