受检者与模式类型不兼容;找到:package.SomeObject 所需:单位

sin*_*ash 4 scala case pattern-matching sbt

我正在尝试 scala 中的文件搜索程序。

文件检查器.scala

package fileSearcher

import sun.org.mozilla.javascript.internal.ast.Yield

class FilterChecker(filter:String) {

def matches(content: String) = content contains filter

def findMatchedFiles(fileObjects: List[IOObject]) =

  for(fileObject <- fileObjects
      if(fileObject.isInstanceOf[FileObject])
      if(matches(fileObject.name)))
    yield fileObject

}

object FilterChecker{

  def apply(filter: String)=new FilterChecker(filter)
}
Run Code Online (Sandbox Code Playgroud)

IOObject.scala

package fileSearcher
import java.io.File
trait IOObject {
  val file:File
  val name= file.getName()
}

case class FileObject(file: File)extends IOObject
case class DirectoryObject(file: File)extends IOObject
Run Code Online (Sandbox Code Playgroud)

文件转换器.scala

package fileSearcher

import java.io.File

object FileConverter {
def convertToIOObject(file: File){
  if(file.isDirectory()) DirectoryObject(file)
  else FileObject(file)
}
}
Run Code Online (Sandbox Code Playgroud)

匹配器.scala

package fileSearcher

import java.io.File

class Matcher(filter:String,rootLocation:String) {
val rootIOObject=FileConverter.convertToIOObject(new File(rootLocation))

def execute()={
  val matchedFiles= rootIOObject  match {
    case file : FileObject if FilterChecker(filter) matches file.name =>List(file)  //error 1
    case directory: DirectoryObject => ???    //error 2
    case _ => List()

  }
  matchedFiles map(iOObject => iOObject.name) 
 }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我 2 个错误。

scrutinee is incompatible with pattern type; found : fileSearcher.FileObject required: Unit
scrutinee is incompatible with pattern type; found : fileSearcher.DirectoryObject required: Unit
Run Code Online (Sandbox Code Playgroud)

谁能解释一下我做错了什么以及如何解决它?

谢谢

dhg*_*dhg 5

您缺少一个等号:

def convertToIOObject(file: File) = {
                                  ^
                                  here
Run Code Online (Sandbox Code Playgroud)

如果没有它,编译器会假定该方法返回Unit,这就是该match语句令人困惑的原因:它不能是 aFileObjectDirectoryObject是否必须是 a Unit