简体   繁体   English

在 Scala 中,我如何反射创建底层类型

[英]in scala how can i reflection creates the underlying type

Let's say I have the following:假设我有以下内容:

val int_string = "Int"

I want to get a map.我想要一张地图。 In the process of running the program, I need to infer its type from the data, and then create a map,like in spark dataframe在运行程序的过程中,我需要从数据中推断出它的类型,然后创建一个地图,就像在spark dataframe中一样

key钥匙 count数数 key_radio key_radio sample_radio sample_radio
1 1 2 2 0.2857142857142857 0.2857142857142857 0.5 0.5
3 3 2 2 0.2857142857142857 0.2857142857142857 0.5 0.5
2 2 3 3 0.42857142857142855 0.42857142857142855 0.5 0.5

I only know the key column is “int”,but how can I create the Int object?我只知道关键列是“int”,但是如何创建Int对象? from the string “Int”来自字符串“Int”

Map[Int,Double] = ???

In val int_string = "Int" the string "Int" is a runtime thing.val int_string = "Int" ,字符串"Int"是运行时的东西。

In val m: Map[Int,Double] = ???val m: Map[Int,Double] = ??? the type Int is a compile-time thing. Int类型是编译时的东西。

Runtime vs. Compile time 运行时与编译时

You can't have Int at compile time (ie earlier) based on information at runtime (ie later).根据运行时(即稍后)的信息,您不能在编译时(即更早)使用Int

You should provide more details how you're going to use Map[Int,Double] , why is Map[Any,Double] not enough etc.您应该提供更多详细信息,您将如何使用Map[Int,Double] ,为什么Map[Any,Double]不够等。

Depending on your use case, Map[Any,Double] (or even Map[Any,Any] ) could be enough or something else can be done or in rare cases, when Int is actually significant, one can use reflective toolbox (creating new compile time inside runtime)根据您的用例, Map[Any,Double] (甚至Map[Any,Any] )可能就足够了,或者可以做其他事情,或者在极少数情况下,当Int实际上很重要时,可以使用反射工具箱(创建新的运行时内的编译时间)

tb.eval(tb.parse(s"val m: Map[$int_string,Double] = ???"))

Scala - looping over case class names to use as type parameters Scala - 循环使用案例类名作为类型参数

Covariant case class mapping to its base class without a type parameter and back协变 case 类映射到它的基类,没有类型参数并返回

Invoke a template Scala function with a type stored as wild card classTag?使用存储为通配符 classTag 的类型调用模板 Scala 函数?

test for membership in Scala type class (2)测试 Scala 类型类中的成员资格(2)

Scala resolving Class/Type at runtime + type class constraint Scala 在运行时解析类/类型 + 类型类约束

scala get generic type by class scala 按类获取泛型类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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