Dal*_*and 5 inheritance scala overloading read-eval-print-loop
接下来,当x.toString失败时,ScalaRunTime.stringOf(x)如何失败?, 怎么
x.toString
Run Code Online (Sandbox Code Playgroud)
不同于
(x: Any).toString
Run Code Online (Sandbox Code Playgroud)
还有,怎么样
"" + x
Run Code Online (Sandbox Code Playgroud)
示例REPL会话:
> 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-15T09:27:17.929+01:00
scala> (dt: Any).toString
res0: String = 2014-05-15T09:27:17.929+01:00
scala> "" + dt
res1: String = 2014-05-15T09:27:17.929+01:00
scala> dt.toString
java.lang.AssertionError: assertion failed: org.joda.convert.ToString
at scala.reflect.internal.Symbols$Symbol.info(Symbols.scala:1410)
at scala.reflect.internal.Symbols$TypeSymbol.isNonBottomSubClass(Symbols.scala:3040)
at scala.reflect.internal.AnnotationInfos$AnnotationInfo.matches(AnnotationInfos.scala:305)
at scala.reflect.internal.AnnotationInfos$Annotatable$class.dropOtherAnnotations(AnnotationInfos.scala:68)
at scala.reflect.internal.AnnotationInfos$Annotatable$class.hasAnnotation(AnnotationInfos.scala:53)
at scala.reflect.internal.Symbols$Symbol.hasAnnotation(Symbols.scala:174)
at scala.tools.nsc.typechecker.Infer$class.improves$1(Infer.scala:61)
at scala.tools.nsc.typechecker.Infer$$anonfun$4.apply(Infer.scala:65)
at scala.tools.nsc.typechecker.Infer$$anonfun$4.apply(Infer.scala:65)
Run Code Online (Sandbox Code Playgroud)
你的另一个问题的答案清楚地描述了问题,我将再给它一个镜头,并更详细地描述发生了什么.
当你调用时,dt.toString你实际上调用了类的toString方法,该方法DateTime还包含此方法的重载版本.这导致编译错误,而不是运行时错误,编译器中实际上是一个错误(但它似乎是在更新的Scala版本中修复,因为其他答案提到)
在的情况下,(dt: Any).toString或"" + dt你不是直接调用的重载一个toString的方法DateTime,但在所定义的一个Any(这实际上是java.lang.Object#toString).编译器甚至没有看到子类的重载toString方法DateTime- 因此相应的bug不会产生任何问题.
在运行时,由于动态调度而不是Any.toString调用的实现DateTime.toString.此调度不是由scalac在编译时完成的,而是由JVM在运行时完成的.后者没有重载错误 - 因此不会发生错误.