【问题标题】:Type mismatch using Jedis in Scala在 Scala 中使用 Jedis 的类型不匹配
【发布时间】:2011-10-19 15:00:22
【问题描述】:

以下代码产生四个类型不匹配错误。为什么?在第一种和第二种情况下,我正在与字符串进行简单的比较。在第三种情况下,我将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 数据库交互。 Jedis.get() 方法返回String。我正在使用 sbt 0.10.1 和 scala 2.9.0-1。

发生了什么事?

【问题讨论】:

  • 我们需要更多的上下文来帮助您弄清楚发生了什么。例如,周围的方法或表达式应该返回什么?编译器在抱怨哪一行/哪一列?
  • 对不起。我添加了有关错误的更多代码和详细信息。谢谢。

标签: scala redis lift jedis


【解决方案1】:

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

//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
}

【讨论】:

  • 这不会回答你的问题,但这里有一些关于为什么你不应该在 finally 块中使用 return 语句的想法。 stackoverflow.com/questions/48088/… 顺便说一句,您可以在 Scala 中省略 return 关键字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-27
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多