【问题标题】:in scala how can i reflection creates the underlying type在 scala 中,我如何反射创建底层类型
【发布时间】:2021-12-07 02:24:16
【问题描述】:

假设我有以下内容:

val int_string = "Int"

我想要一张地图。在运行程序的过程中,我需要从数据中推断出它的类型,然后创建一个map,就像在spark dataframe中一样

key count key_radio sample_radio
1 2 0.2857142857142857 0.5
3 2 0.2857142857142857 0.5
2 3 0.42857142857142855 0.5

我只知道键列是“int”,但是如何创建Int 对象呢?来自字符串“Int”

Map[Int,Double] = ???

【问题讨论】:

    标签: scala apache-spark scala-reflect


    【解决方案1】:

    val int_string = "Int" 中,字符串"Int" 是运行时的东西。

    val m: Map[Int,Double] = ??? 中,Int 类型是编译时的东西。

    Runtime vs. Compile time

    根据运行时(即稍后)的信息,您不能在编译时(即更早)拥有Int

    你应该提供更多细节你将如何使用Map[Int,Double],为什么Map[Any,Double]不够等等。

    根据您的用例,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

    Covariant case class mapping to its base class without a type parameter and back

    Invoke a template Scala function with a type stored as wild card classTag?

    test for membership in Scala type class(2)

    Scala resolving Class/Type at runtime + type class constraint

    scala get generic type by class

    【讨论】:

    • 我的主要问题是如何在代码运行过程中通过获取到的字符串中的类型来创建一个case类
    • @user3167604 为什么需要案例类?你打算如何使用它?为什么Map[Any,Double]Map[Any,Any] 还不够?
    猜你喜欢
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    相关资源
    最近更新 更多