Construct a function to return the default value of any type:
import scala.compiletime.uninitialized
def default[T]:T = {
class Default[T] { var value:T = uninitialized }
Default[T].value
}
default[Double] // Double = 0.0
default[Boolean] // Boolean = false
default[Int] // Int = 0
This pattern match does not work (why?):
def matchType[T]():T = {
default[T] match {
case d:Double => d
case i:Int => i
case b:Boolean => b
}
}
matchType[Double]()
scala.MatchError: null
ammonite.$sess.cmd37$.matchType(cmd37.sc:5)
ammonite.$sess.cmd37$.<clinit>(cmd37.sc:9)
Why is the pattern match failing?
In both cases (top case: using default[Double] and bottom case: using matchTypeDouble) everything is known at compile time.
Motivation for this question: convert a string to a type where you specify the type T, then use pattern match to handle different functionality at runtime. e.g. fromStringToDouble would pattern match on the Double (using default[Double]) and use functionality at runtime to convert “3.14” to 3.14:Double using e.g. toString
George Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.