How is ScalaRunTime.stringOf(x) not failing when x.toString fails?

旧街凉风 提交于 2019-12-12 09:42:26

问题


Whilst trying to figure out some joda-time DateTime (timestamp formatting) issues I opened a REPL with

scala -cp joda-time-2.3.jar

and forgot to add the joda-convert jar, and eventually got a

java.lang.AssertionError: assertion failed: org.joda.convert.ToString

(The entire stacktrace)

I was able to simplify this to:

> scala -cp joda-time-2.3.jar
Welcome to Scala version 2.11.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_05).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val dt = new org.joda.time.DateTime
warning: Class org.joda.convert.FromString not found - continuing with a stub.
warning: Class org.joda.convert.ToString not found - continuing with a stub.
warning: Class org.joda.convert.FromString not found - continuing with a stub.
warning: Class org.joda.convert.ToString not found - continuing with a stub.
dt: org.joda.time.DateTime = 2014-05-14T17:54:24.511+01:00

scala> scala.runtime.ScalaRunTime.stringOf(dt)
res0: String = 2014-05-14T17:54:24.511+01:00

scala> dt.toString
java.lang.AssertionError: assertion failed: org.joda.convert.ToString

How is ScalaRunTime.stringOf(dt) succeeding where dt.toString fails?


回答1:


You didn't post the stack trace, which is a compiler crash and not a failed assertion by joda.

The REPL is crashing compiling the expression.

It looks like AbstractDateTime has an overloaded toString method, and overload resolution crashes on the @ToString annotation on the usual toString(). (The symbol for ToString is missing.)

But stringOf(x: Any) is just invoking Object.toString(), of course.

There are some known issues, apparently. A recent issue was fixed.

On 2.10.4:

scala> (dt: Any).toString
res0: String = 2014-05-14T11:56:21.794-07:00

scala> dt.toString
<console>:9: error: ambiguous reference to overloaded definition,
both method toString in class AbstractDateTime of type (x$1: String, x$2: java.util.Locale)String
and  method toString in class AbstractDateTime of type (x$1: String)String
match expected type ?
              dt.toString
                 ^

scala> dt.toString()  // crashes

2.10.3 is bumpier and claims error while loading DateTime, class file is broken.

The crash is on 2.11.0.



来源:https://stackoverflow.com/questions/23660990/how-is-scalaruntime-stringofx-not-failing-when-x-tostring-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!