Scala specs2匹配文件的扩展名

时间:2012-07-18 09:17:18

标签: scala matcher specs2

我正在尝试创建一个specs2匹配器来断言File扩展的有效性(通过重用现有的endWith匹配器)。但是我得到了一个类型错误。我怎么能绕过它?

import java.io.File
import org.specs2.mutable.Specification
import org.specs2.matcher.{ Expectable, Matcher }

class SampleSpec extends Specification {
  def hasExtension(extension: => String) = new Matcher[File] {
    def apply[S <: File](actual: Expectable[S]) = {
      actual.value.getPath must endWith(extension)
    }
  }
}

这是编译器错误:

<console>:13: error: type mismatch;
 found   : org.specs2.matcher.MatchResult[java.lang.String]
 required: org.specs2.matcher.MatchResult[S]
             actual.value.getPath must endWith(extension)

2 个答案:

答案 0 :(得分:2)

你确实可以使用^^运算符(从解析器组合子运算符中获取灵感)并简单地写:

def hasExtension(extension: =>String) = endWith(extension) ^^ ((_:File).getPath)

作为参考,我们提供了创建自定义匹配器的各种方法here

答案 1 :(得分:0)

好的,我已经通过使用适应匹配器类型的^^运算符来实现它。它看起来像是一个仿函数的地图函数。

def hasExtension(extension: => String) = new Matcher[File] {
  def apply[S <: File](actual: Expectable[S]) = {
    actual must endWith(extension) ^^ ((file: S) => file.getPath)
  }
}