Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala create a numeric from a string

Tags:

scala

I want to do something like this:

def parse[A: Numeric](str: String): A = {
   if A =:= Int, str.toInt
   if A =:= Float, str.toFloat
   if A =:= BigInt, BigInt(str)
   ...
   ...
}

Unfortunately, it seems that there is no fromString defined in the Numeric trait. What is the most idiomatic way to achieve this in Scala?

like image 655
pathikrit Avatar asked Dec 05 '25 09:12

pathikrit


1 Answers

What you're asking for is in general impossible by the extendable nature of typeclasses; there is no way you could match against all possible implementations of Numeric because any user-defined type could implement it. Likewise because of that, it's not guaranteed that every Numeric[A] is parseable from a string.

There's two ways out of this. One is a partial solution where you make sure you only use strings representing integer literals, then use Int's fromString to parse it and Numeric's fromInt to convert it.

The other way is to pass in the actual string parsing function when the function is called. This can kind of feel like cheating as your parse method no longer does any real work, but can be made to be quite useful with implicits.

The most straightforward way is to just add a (maybe implicit) String -> A parameter (or maybe String -> Option[A] for fewer runtime errors). Another way of achieving this is to go the the typeclass route again and implement something like a Readable typeclass. Then you can have your function be the following:

def parse[A: Numeric: Readable](x: String): A = ...

Now you just need to make sure you have Readable[A] implementations for all the A you care about.

like image 68
badcook Avatar answered Dec 06 '25 22:12

badcook