【发布时间】:2015-11-03 23:05:47
【问题描述】:
要将字符串解析为 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 类型,那么类型标签会阻止其类型被擦除。但在这里,我想这样称呼它:
tryParsing[Boolean]("1") // value from variable
我如何匹配类型或做我在 scala 2.10 中尝试做的事情?
【问题讨论】:
-
使用类似
def parse(x: String) = Try(x.toBoolean).orElse(Try(x.toInt)).get的东西。要返回默认值,请使用getOrElse。 -
我需要增加累加器并在解析错误时记录错误,所以我想集中该逻辑。我必须解析大量(
标签: scala