-1

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

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

I only know the key column is “int”,but how can I create the Int object? from the string “Int”

Map[Int,Double] = ???

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
season
  • 31
  • 5

1 Answers1

1

In val int_string = "Int" the string "Int" is a runtime thing.

In val m: Map[Int,Double] = ??? the type Int is a compile-time thing.

Runtime vs. Compile time

You can't have Int at compile time (i.e. earlier) based on information at runtime (i.e. later).

You should provide more details how you're going to use Map[Int,Double], why is Map[Any,Double] not enough etc.

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)

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

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • My main problem is how to create a case class through the types in the obtained string during code running – season Oct 25 '21 at 07:44
  • @user3167604 Why do you need a case class? How are you going to use it? Why `Map[Any,Double]` or `Map[Any,Any]` is not enough? – Dmytro Mitin Oct 25 '21 at 08:23