简体   繁体   English

Scala类型不匹配什么时候不应该?

[英]Scala type mismatch when it shouldn't?

I have these two functions in scala: 我在scala中具有以下两个功能:

def recursive_func(x: Position, count: Int) : Int = {
      if(getNewPositions(x).isEmpty){
        count + 1;
      } else {
        for(n <- getNewPositions(x)){
          recursive_func(n, count+1);
        }
      }
}

def getNewPositions(x: Position) : List[Position] = {
    val possible : List[Position] = List((x._1 + 5,x._2 + 6), (x._1 + 6,x._2 + 7), (x._1 + 7,x._2 + 8), (x._1 + 8, x._2 + 9));
    val answer : List[Position] = for (n <- possible if canMakeMove(n)) yield n;
    answer;
}

The second returns a List of positions which is sometimes empty. 第二个返回的职位列表有时为空。 The first is a recursive function that should return 1 if the list returned by getNewPositions is empty, or iterate over it if the list is not. 第一个是递归函数,如果getNewPositions返回的列表为空,则应返回1;如果列表不是,则在其上进行迭代。 However I'm getting this error: 但是我收到此错误:

error: type mismatch;
 found   : Unit
 required: Int

which I presume is because the compiler is trying to do for(n <- getNewPositions(x)) on an empty list even though in my head it shouldnt because of the if statement it's wrapped in? 我认为这是因为编译器试图在一个空列表上执行(n <-getNewPositions(x)),即使在我的脑海中,由于它被包裹在if语句中,所以它不应该这样做? I know for sure that the getNewPositions function works fine and returns the appropriate list. 我肯定知道getNewPositions函数可以正常工作并返回适当的列表。 Any help would be appreciated. 任何帮助,将不胜感激。

There are 2 errors in your code: 您的代码中有2个错误:

  1. First: 第一:

    for(n <- getNewPositions(x)){ recursive_func(n, count+1); }

    Type of this expression is unit (this is causing your compilation error). 该表达式的类型是单位(这会导致您的编译错误)。 Reason: for (n <- coll) {..} expands to coll.foreach(n => {..}) 原因: for (n <- coll) {..} coll.foreach(n => {..}) for (n <- coll) {..}扩展为coll.foreach(n => {..})

  2. Second: for (n <- possible canMakeMove(n)) yield {} is definitly not a valid scala syntax 第二: for (n <- possible canMakeMove(n)) yield {}绝对不是有效的scala语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM