如何将案例类作为变量传递到ScalaReflection [英] How to pass case class as a variable into ScalaReflection
问题描述
我试图将案例类作为变量传递给ScalaReflection以获取架构.
I am trying to pass a case class as a variable to ScalaReflection to get the schema.
我能够使用案例类名称成功运行代码,就像将案例类分配给变量并将其传递给ScalaReflection一样,我遇到了错误.
I am able to run the code successfully with case class name where as when I assign the case class to a variable and pass that to ScalaReflection I am getting error.
这是我的代码
import org.apache.spark.sql.catalyst.ScalaReflection
import org.apache.spark.sql.types.StructType
case class Emp (empId: Integer, empName: String)
val myschema = ScalaReflection.schemaFor[Emp].dataType.asInstanceOf[StructType]
println(myschema)
val empModel = Emp
val myschema2 = ScalaReflection.schemaFor[empModel].dataType.asInstanceOf[StructType]
Error: error: not found: type empModel
val myschema2 = ScalaReflection.schemaFor[empModel].dataType.asInstanceOf[StructType]
任何建议都是有帮助的!
Any suggestion is helpful!
推荐答案
类型同义词(=别名)应使用关键字 type
Type synonyms (= aliases) should be introduced with a keyword type
type empModel = Emp
val myschema2 = ScalaReflection.schemaFor[empModel].dataType.asInstanceOf[StructType]
在Scala中,值和类型构成不同的名称空间.
In Scala values and types make different namespaces.
具有 type
(和 val
)的顶级定义,因此它们必须位于某个对象之内
Top definitions with type
(and val
) are not allowed in Scala 2, so they have to be inside some object
object App {
type empModel = Emp
val myschema2 = ScalaReflection.schemaFor[empModel].dataType.asInstanceOf[StructType]
}
这篇关于如何将案例类作为变量传递到ScalaReflection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!