0

以下代码产生四个类型不匹配错误。为什么?在第一种和第二种情况下,我正在与字符串进行简单的比较。在第三种情况下,我分配false给一个 var 类型Boolean。在最后一种情况下,我只是打印一个堆栈跟踪!

我很困惑。

编码:

//return TRUE if logged in
def isLoggedIn(auth: String): Boolean = {
    val jedis = pool.getResource()
    var userid = jedis.get("auth:" + auth)
    var retVal = false
    try {
        if(userid != null) { //error here
            val userAuth = jedis.get("uid:" + userid + ":auth")
            if(userAuth == auth) { // error here
                retVal = true // error here
            }
        }
    } catch {
        case e => e.printStackTrace() //error here
    } finally {
        pool.returnResource(jedis)
        return retVal
    }
}

错误:

[error] type mismatch;
[error]  found   : Unit
[error]  required: Boolean
[error]                     retVal = true // error here
[error]                            ^
[error] type mismatch;
[error]  found   : Unit
[error]  required: Boolean
[error]                 if(userAuth == auth) { // error here
[error]                 ^
[error] type mismatch;
[error]  found   : Unit
[error]  required: Boolean
[error]             if(userid != null) { //error here
[error]             ^
[error] type mismatch;
[error]  found   : Unit
[error]  required: Boolean
[error]             case e => e.printStackTrace() //error here
[error]                                        ^
[error] four errors found

我正在使用 Jedis 2.0.0 (https://github.com/xetorthio/jedis) 与 Redis DB 交互。Jedis.get() 方法返回String. 我正在使用 sbt 0.10.1 和 scala 2.9.0-1。

这是怎么回事?

4

1 回答 1

0

解决它。需要return从 try/catch/finally 中移出。这是更新的代码,编译得很好。我挥之不去的问题是:为什么不能return在最后?

//return TRUE if logged in
def isLoggedIn(auth: String): Boolean = {
    val jedis = pool.getResource()
    var userid = jedis.get("auth:" + auth)
    var retVal = false
    try {
        if(userid != null) { 
            val userAuth = jedis.get("uid:" + userid + ":auth")
            if(userAuth == auth) { 
                retVal = true 
            }
        }
    } catch {
        case e => e.printStackTrace()
    } finally {
        pool.returnResource(jedis)
    }
    return retVal
}
于 2011-08-04T15:49:25.693 回答