加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如何在模式匹配时摆脱“由于擦除而未检查”警告

发布时间:2020-12-16 09:05:34 所属栏目:安全 来源:网络整理
导读:Scala 2.8.1 我使用解析器/组合器实现了一个非常简单的外部DSL,用于QA编写验收测试. 最近我添加了循环遍历一组表达式的能力 sealed trait Expr...//insert other case classes extending 'Expr' here...case class Repetition(times: Int,expressions: List[
Scala 2.8.1

我使用解析器/组合器实现了一个非常简单的外部DSL,用于QA编写验收测试.

最近我添加了循环遍历一组表达式的能力

sealed trait Expr

...
//insert other case classes extending 'Expr' here
...

case class Repetition(times: Int,expressions: List[Expr]) extends Expr

class TestFixtureParser(....) extends RegexParsers {
  val repeatParser: Parser[Expr] = (l("repeat") ~> number) ~ (l("{") ~> expressions <~ l("}")) ^^ {
    case (times: Int) ~ (exprs: List[Expr]) => {
      Repetition(times,exprs)
    }
  }

  private val expressions: Parser[List[Expr]] = (repeatParser | 
    /*insert other Parser[Expr]s '|' together here */ | verifyParser ).*

}

在构建时,我收到警告警告:非变量类型参数…未选中,因为在模式匹配时通过擦除消除了它.我也尝试使用以下方法进行提取.

//Doesn't build with error
  /*
    error: missing parameter type for expanded function ((x0$2) => x0$2 match {
      case $tilde((times @ _),(exprs @ _)) => Repetition(times,exprs)
    })
        r: ~[Int,List[Expr]] => {
  */
  val repeatParser: Parser[Expr] = (l("repeat") ~> number) ~ (l("{") ~> expressions <~ l("}")) ^^ {
    r: ~[Int,List[Expr]] => {
      case times ~ exprs =>
        Repetition(times,exprs)
    }
  }

  //Actually this does build without warning. 
  //I am unfortunately using intelliJ and it doesn't like it
  val repeatParser: Parser[Expr] = (l("repeat") ~> number) ~ (l("{") ~> expressions <~ l("}")) ^^ {
    repetitions: ~[Int,List[Expr]] => {
      val ~(times,exprs) = repetitions
      Repetition(times,exprs)
    }
  }

  //Builds but same warning
  val repeatParser: Parser[Expr] = (l("repeat") ~> number) ~ (l("{") ~> expressions <~ l("}")) ^^ {
    repetitions => {
      val ~(times: Int,exprs: List[Expr]) = repetitions
      Repetition(times,exprs)
    }
  }

有没有人有任何建议在没有这个警告的情况下以优雅的方式提取exprs?它确实起作用.我应该忽略它吗?我不想养成忽视警告的习惯.

编辑:答案.这实际上是我先尝试但后来我添加了类型因为intelliJ scala插件无法推断它们.

val repeatParser: Parser[Expr] = (l("repeat") ~> number) ~ (l("{") ~> expressions <~ l("}")) ^^ {
      case times ~ exprs =>
          Repetition(times,exprs)
  }

解决方法

我认为你的语法不适合第一个“不构建”的例子(看起来你正在返回一个部分函数而不是应用它,这不是你想要的).尝试
写作:

val repeatParser: Parser[Expr] = (l("repeat") ~> number) ~ (l("{") ~> expressions <~ l("}")) ^^ {
    case times ~ exprs =>
        Repetition(times,exprs)
}

我担心我无法测试这个,因为我没有其余的代码取决于,但这种结构通常有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读