当x.toString失败时,ScalaRunTime.stringOf(x)如何不失败?

前端之家收集整理的这篇文章主要介绍了当x.toString失败时,ScalaRunTime.stringOf(x)如何不失败?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在尝试找出一些joda-time DateTime(时间戳格式化)问题的同时,我打开了一个REPL

scala -cp joda-time-2.3.jar

并忘记添加joda-convert jar,最终得到了一个

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

(The entire stacktrace)

我能够将其简化为:

> 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

ScalaRunTime.stringOf(dt)如何在dt.toString失败的地方成功?

解决方法

你没有发布堆栈跟踪,这是一个编译器崩溃,而不是joda失败的断言.

REPL正在崩溃编译表达式.

看起来AbstractDateTime有一个重载的toString方法,并且重载分辨率在通常的toString()上的@ToString注释上崩溃. (缺少ToString的符号.)

但是stringOf(x:Any)当然只是调用Object.toString().

显然有some known issues. recent issue修复了.

在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在加载DateTime时更加颠覆并声称错误,类文件被破坏.

崩溃发生在2.11.0.

猜你在找的Scala相关文章