在Scala中使用Jedis键入不匹配

时间:2011-08-04 02:54:24

标签: scala redis lift jedis

以下代码会产生四种类型不匹配错误。为什么?在第一和第二种情况下,我正在与字符串进行简单的比较。在第三种情况下,我将false分配给变种类型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。

发生了什么事?

1 个答案:

答案 0 :(得分: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
}