[英]Android Room Bug in Kotlin
I think the is a semantic issue in Room while working in Kotlin.我认为这是在使用 Kotlin 时 Room 中的语义问题。 Simple
DAO
query in Room can be obtained by Room中简单的
DAO
查询可以通过
@Query("SELECT * FROM Users WHERE id = :id")
fun getUser(id: Int): User
Although, I defined return type as User
, not User?
虽然,我将返回类型定义为
User
,而不是User?
, this query can still returns null, when there is no User with the given id . ,当没有具有给定id 的用户时,此查询仍然可以返回 null。
So whenever you call this function, you definitely need to check for null
return, as below所以每当你调用这个函数时,你肯定需要检查
null
返回,如下
val user = userDao.getUser("someid")
if (user != null){
return user
}
else {
return DEFAULT_USER
}
But since we defined return type of getUser
as User
, @kotlin compiler suggest that null
check is redundant .但是由于我们将
getUser
返回类型定义为User
,@kotlin 编译器建议null
检查是多余的。
Am I missing something?我错过了什么吗? Can anyone give some feedback on this?
任何人都可以对此提供一些反馈吗?
There is no semantic issue.没有语义问题。 If Your function can return a null, it should be defined in the function return type.
如果您的函数可以返回空值,则应在函数返回类型中定义它。 So, your function signature should be like this
所以,你的函数签名应该是这样的
fun getUser(id: Int): User?
This means the function can return null and now your null checks should work fine.这意味着该函数可以返回 null,现在您的 null 检查应该可以正常工作。
Apparently it's already tracked issue in Google Issue Tracker And as a respond they developers say显然它已经在谷歌问题跟踪器中跟踪问题 作为回应他们开发人员说
Status: Won't Fix (Intended Behavior)
状态:无法修复(预期行为)
this is not about generated code though, you are the person who creates that Query method so you should declare it as nullable.
不过,这与生成的代码无关,您是创建该 Query 方法的人,因此您应该将其声明为可为空的。
So, if we know that our code can return null
, we should declare it as Nullable
as所以,如果我们知道我们的代码可以返回
null
,我们应该将其声明为Nullable
为
@Query("SELECT * FROM Users WHERE id = :id")
fun getUser(id: Int): User?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.