【问题标题】:Parsing a String to Boolean or Int将字符串解析为 Boolean 或 Int
【发布时间】: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
        }
    }
  }

我无法匹配类型标签。我猜这是因为如果valueT 类型,那么类型标签会阻止其类型被擦除。但在这里,我想这样称呼它:

tryParsing[Boolean]("1")         // value from variable

我如何匹配类型或做我在 scala 2.10 中尝试做的事情?

【问题讨论】:

  • 使用类似def parse(x: String) = Try(x.toBoolean).orElse(Try(x.toInt)).get的东西。要返回默认值,请使用getOrElse
  • 我需要增加累加器并在解析错误时记录错误,所以我想集中该逻辑。我必须解析大量(

标签: scala


【解决方案1】:

使用类型类模式:

trait Parser[T] {
  def parse(input: String): Option[T]
}

def parse[T](input: String)(implicit parser: Parser[T]): Option[T] =
  parser.parse(input)

import util.Try
implicit object IntParser extends Parser[Int] {
  def parse(input: String) = Try(input.toInt).toOption
}
implicit object BooleanParser extends Parser[Boolean] {
  def parse(input: String) = Try(input.toBoolean).toOption
}

瞧:

scala> parse[Int]("3")
res0: Option[Int] = Some(3)

scala> parse[Int]("zzz")
res1: Option[Int] = None

scala> parse[Boolean]("true")
res2: Option[Boolean] = Some(true)

scala> parse[Boolean]("zzz")
res3: Option[Boolean] = None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2014-01-06
    相关资源
    最近更新 更多