Xiangyu
Xiangyu

Reputation: 844

The difference between running a scala script directly vs through a scala shell

I ran into the "No TypeTag available for" error when running a simple script:

import scala.reflect.runtime.{universe => ru} 
case class Person(name: String)
val classPerson = ru.typeOf[Person].typeSymbol.asClass

The script is an example from Scala Reflection Doc. According to this post, the error is caused by the fact that the case class is not defined at the top level. I know scala automatically compiles a scala script into a class before running it, thus making the case class a internally defined class, but the same script would work if it is run in a scala shell. So what is the difference between running a scala script and running the same script through the scala shell?

Upvotes: 0

Views: 98

Answers (1)

Leo C
Leo C

Reputation: 22449

I'm not sure there is discrepancy between the Scala Shell and a Scala program in this case. It still wouldn't work if the case class isn't defined "top-level" in the shell:

scala> import scala.reflect.runtime.{universe => ru} 
import scala.reflect.runtime.{universe=>ru}

scala> case class Something(name: String)
defined class Something

scala> ru.typeOf[Something].typeSymbol.asClass
res1: reflect.runtime.universe.ClassSymbol = class Something

scala> { case class Something(name: String); ru.typeOf[Something].typeSymbol.asClass }

<console>:16: error: No TypeTag available for Something
    { case class Something(name: String); ru.typeOf[Something].typeSymbol.asClass }
                                                  ^

[EDIT] Response to comments appended below:

It'll work in a program too as long as the case class is defined "top-level". The following code will compile and output the class name:

import scala.reflect.runtime.{universe => ru} 

case class Something(name: String)

object MyReflection extends App {
  println ("My case class: " + ru.typeOf[Something].typeSymbol.asClass)
}

Upvotes: 1

Related Questions