我正在寻找一种通用的函数方法,可以在Scala字符串与任何数字类型之间进行转换。如果无法通过默认值,我需要。
例如,我需要从转换为String,Int但万一将String转换为Int失败。我需要传递默认值而无需throws java.lang.NumberFormatException。我尝试过这种方式,但是没有得到我的想法,因为我需要通用的,并且在出现异常的情况下也使用默认值
编辑:我更新了解决方案以从任何类型解析为任何类型。这使解决方案根据所请求的问题变得更加通用。我认为您可以使用Scala功能方法来具有泛型类型,[T]但需要将其分为两部分。
首先实现解析类型,将任何类型解析[U]为任何类型[T]。使用Scala函数方式parseTypes将函数canBuildFrom作为参数。然后,根据此函数的输出,您将检查它是否正确解析或是否有异常。另外,如果解析失败,您可以传递默认参数。
def parseTypes[T,U](str: U, canBuildFrom: U ? T): Either[java.lang.NumberFormatException, T] =
Try(canBuildFrom(str)).map(Right(_)).getOrElse {
Left(new java.lang.NumberFormatException(str.toString))
}
def safeParse[T,U](attributeValue: U, canBuildFrom: U ? T, defaultValue: T): T = {
parseTypes(attributeValue, canBuildFrom) match {
case Right(x) ? x
case Left(x) ? defaultValue
case _ ? defaultValue
}
}
def safeParseDoubleToBigDecimal(attributeValue: Double): BigDecimal = safeParse[BigDecimal,Double](attributeValue, toBigDecimal, 0.0)
Run Code Online (Sandbox Code Playgroud)
您可以使用它来将String解析为Int,Double和Decimal,如下所示:
def safeParseStringToInt(attributeValue: String): Int = safeParse[Int,String](attributeValue, _.toInt, 0)
def safeParseStringToDouble(attributeValue: String): Double = safeParse[Double ,String](attributeValue, _.toDouble, 0.0)
def safeParseStringToBigDecimal(attributeValue: String): BigDecimal = safeParse[BigDecimal ,String](attributeValue, BigDecimal(_), 0.0)
// example of usage
val x:Int = safeParseStringToInt("123",0)
val y:Int = safeParseStringToInt("aaa",0)
Run Code Online (Sandbox Code Playgroud)