2017-11-25 131 views
5

我有以下方法。它的逻辑非常简单,如果设置了正确的值,那么在它有一个值(非空值)时调用左边的值。当我按照以下方式编写它时,它会起作用。Kotlin编译器无法确定该变量在可执行循环中是不可空的

fun goNext(from: Node): Node? { 
    var prev : Node = from 
    var next : Node? = from.right 
    if (next != null) { 
     prev = next 
     next = next.left 
     while (next != null) { 
      prev = next 
      next = next.left 
     } 
    } 
    return prev 
} 

相反,如果我尝试使用do-while循环,缩短了代码,它不再智能蒙上nextNode。它显示了这个错误:

Type mismatch. 
Required: Node<T> 
Found: Node<T>? 

的代码如下:

fun goNext(from: Node): Node? { 
    var prev : Node = from 
    var next : Node? = from.right 
    if (next != null) { 
     do { 
      prev = next // Error is here, even though next can't be null 
      next = next.left 
     } while (next != null) 
    } 
    return prev 
} 
+2

为什么不简化为只是'while(next!= null){...}'? –

+0

你是对的!我没有看到它。 – biowep

回答

-1

编译器可能会假设接下来可以if语句,并从另一个线程环路之间变化。 既然你可以保证下一个不是null,只需加上!!当在循环中使用它时:next!

+0

然后它也可以改变,而条件和assingment'prev = next' – biowep

+0

@biowep prev = next !!应该适合,不应该吗? – Zonico

+0

当然,它确实存在,但它是围绕非连贯行为的工作,它也引入了非必要的控制。 – biowep

相关问题