1
要将字符串解析为int,我们可以执行theString.toInt
和布尔值theString.toBoolean
。我怎样才能使这个通用?将字符串解析为布尔值或整数
我想以某种方式进行参数化的功能,这样我可以尝试解析字符串作为一个布尔值或者int,处理错误和返回的错误违约等
我有这样的:
def tryParsing[T: TypeTag](value: String)(implicit errorAccumulator: Accumulator[Int]): Option[T] = {
// scala's .toBoolean only permits exactly "true" or "false", not numeric booleans.
val validBooleans = Map(
"true" -> true,
"false" -> false,
"1" -> true,
"0" -> false
)
import scala.reflect.runtime.universe._
// doesn't work. Also, using TypeTag doesn't seem to work.
typeOf[T] match {
case t if t <:< typeOf[Boolean] =>
val result = validBooleans.get(value.asInstanceOf[String].toLowerCase)
if (result.isEmpty) {
logger.warn(s"An error occurred parsing the boolean value `$value`")
errorAccumulator += 1
}
result.asInstanceOf[Option[T]]
case _ =>
Try(value.asInstanceOf[T]) match {
case Success(x) => Some(x: T)
case Failure(e) =>
logger.warn(s"An parsing error occurred: $e")
errorAccumulator += 1
None
}
}
}
我无法匹配类型标记。我想这是因为如果value
是T
类型,那么typetag会阻止它的类型被删除。但在这里,我想打电话给此类似:
tryParsing[Boolean]("1") // value from variable
我怎么能匹配类型或以其他方式做什么,我想在斯卡拉2.10办?
使用像'高清解析(X:字符串)=尝试(x.toBoolean).orElse(TRY(x.toInt ))。GET'。要返回默认值,请使用'getOrElse'。 –
我需要增加累加器和日志分析错误的错误,所以我想集中该逻辑。我必须解析大量(<20)不同的数据位。 – jbrown