简体   繁体   中英

scala: FOO cannot be cast to FOO

In Scala, I am incredibly confused by this fairly tautological error message:

java.lang.ClassCastException: FOO cannot be cast to FOO

I would expect that someone can always be cast to its own type.


Context

I am trying to run the following wrapper around the scala compiler, located at http://code.google.com/p/rooscaloo/source/browse/trunk/rooscaloo/src/org/darevay/rooscaloo/Interpreter.scala Unfortunately, Scala is saying ResultHolder cannot be cast to ResultHolder when I do the following:

import org.darevay.rooscaloo._
println(new Interpreter().eval("2"))

I thought println was supposed to accept Any . What should be going on is that Interpreter.eval returns a ResultHolder type, such that ResultHolder.value would be equal to 2 .

Additionally, trying to print .value doesn't work with the error:

(fragment of Test.scala):3: error: value value is not a member of Any                                                                                                                                                 
println(new Interpreter().eval("2").value)

More details

java.lang.reflect.InvocationTargetException                                                                                                                                                                           
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        ...
Caused by: java.lang.ClassCastException: org.darevay.rooscaloo.ResultHolder cannot be cast to org.darevay.rooscaloo.ResultHolder
        at binder0$.set(<script>:1)
        at binder0.set(<script>)
        ... 24 more (unsure how to print them)

Though I am a Scala newbie, perhaps the internal mechanism binder of the scala.tools.nsc.interpreter package is trying to do something weird.

I'm invoking the script as scala Test.scala .


Question

My question is: What is the cause of this error message, what is the real issue, and how does one get working sample code for scala.tools.nsc.[interpreter]? Thanks.

I've run into similar issue, and I've converted my code to use IMain#mostRecentVar introduced in Scala 2.9. Here's from CompilerMatcher I wrote:

  val main = new IMain(s)
  main.compileSources(files.map(toSourceFile(_)): _*)
  code map { c => main.interpret(c) match {
    case IR.Error => error("Error interpreting %s" format (c))
    case _ => 
  }}
  val recent = main.mostRecentVar
  val holder = main.valueOfTerm(recent)
  if (holder != Some(expected))
    println("actual: " + holder.map(_.toString).getOrElse{"None"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM