I want to read in a CSV file with data and an accompanying CSV file with the types of each column in the first file and cast the data types appropriately. Example:
data file:
a,b,c
1,two,3.333
types file:
column, type
a, int
b, string
c, double
My attempt so far has been to write a function that determines the correct conversion function from a String to the appropriate type. The problem is, the "appropriate type" can be multiple different possible types, depending on the input.
def converter[T](columnType: String): String => T = {
columnType match {
case "int" => (s: String) => s.toInt
case "double" => (s: String) => s.toDouble
case "string" => (s: String) => s
}
}
This does not compile because the type T cannot be inferred.
I looked into the possibility of using the Either keyword but the syntax becomes cumbersome with more than 2 possible return types.
Is there a nice way to do this?
Tdepends on the runtime value ofcolumnTypeTwill be one of multiple types, e.g.Int,Double,String? I can do that sloppily usingEither[Int,Either[Double,String]]but that gets ugly very quickly...