scrutinee与图案类型不相容;发现:package.SomeObject required:Unit

时间:2015-03-03 18:46:01

标签: scala pattern-matching sbt case

我正在scala中尝试一个filesearcher程序。

FileChecker.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)
}

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

FileConverter.scala

package fileSearcher

import java.io.File

object FileConverter {
def convertToIOObject(file: File){
  if(file.isDirectory()) DirectoryObject(file)
  else FileObject(file)
}
}

Matcher.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) 
 }
}

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

scrutinee is incompatible with pattern type; found : fileSearcher.FileObject required: Unit
scrutinee is incompatible with pattern type; found : fileSearcher.DirectoryObject required: Unit

有人可以解释一下我做错了什么以及如何解决?

由于

1 个答案:

答案 0 :(得分:4)

你错过了一个等号:

def convertToIOObject(file: File) = {
                                  ^
                                  here

没有它,编译器会假定该方法返回Unit,这就是match语句混淆的原因:它不能是FileObjectDirectoryObject它必须是Unit