Fixing error: edu.stanford.nlp.ling.CoreLabel cannot be cast to scala.runtime.Nothing$

In Scala, you can get an error like this:

edu.stanford.nlp.ling.CoreLabel cannot be cast to scala.runtime.Nothing$

E.g.:

val types =
  results.map(
    (res) => {
      res.map(
        (label) => label.asInstanceOf[CoreLabel].category()
      )
    }
  )
Exception in thread "main" java.lang.ClassCastException: edu.stanford.nlp.ling.CoreLabel cannot be cast to scala.runtime.Nothing$
	at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
	at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
	at scala.collection.Iterator$class.foreach(Iterator.scala:727)
	at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
	at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
	at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
	at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
	at scala.collection.AbstractTraversable.map(Traversable.scala:105)
	at Speaker$.$anonfun$main$3(Speaker.scala:65)
	at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
	at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
	at scala.collection.Iterator$class.foreach(Iterator.scala:727)
	at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
	at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
	at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
	at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
	at scala.collection.AbstractTraversable.map(Traversable.scala:105)
	at Speaker$.$anonfun$main$2(Speaker.scala:63)
	at Speaker$.$anonfun$main$2$adapted(Speaker.scala:43)
	at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
	at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
	at scala.collection.immutable.List.foreach(List.scala:318)
	at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
	at scala.collection.AbstractTraversable.map(Traversable.scala:105)
	at Speaker$.main(Speaker.scala:42)
	at Speaker.main(Speaker.scala)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

I found that this was fixable by converting the list to an array first:

val types =
  results.map(
    (res) => {
      res.toArray().map(
        (label) => label.asInstanceOf[CoreLabel].category()
      )
    }
  )

Leave a Reply

Your email address will not be published. Required fields are marked *