![](/img/trans.png)
[英]Using def/val/var and how to define the null element in a linked list
[英]How to define count without using var
我有这个简单的函数,返回一些Status
:
def getStatus : String =
{
//...
}
我想等到此返回特定状态,但在退出之前仍要计算此呼叫次数:
def wait =
{
var count = 0
while (getStatus != "smeStatus" && count < 10) {
// some code here
count++
}
}
如何避免使用var
?
您可以使用一种递归方法,该方法采用至今计数并返回+ 1:
def waitUntilDone(countSoFar: Int): Int = {
if (getStatus != "smeStatus" && countSoFar < 10) {
// some code here
waitUntilDone(countSoFar + 1)
} else {
countSoFar
}
}
// invoke it starting with 0:
val count = waitUntilDone(0)
def status = ""
def waiting: Unit = {
def check(count: Int): Unit = {
if(count < 10 && status != "smeStatus") {
// do something
check(count + 1)
}
}
check(0)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.