我正在构建一个体育应用程序并在编译期间遇到问题。 getCachedSubmission函数中的submission变量为null,似乎需要一个null句柄,但我不确定。这是下面的代码:
import com.bluebeam.premierleaguego.features.model.SubmissionWrapper
import com.bluebeam.premierleaguego.data.reddit.RedditAuthentication
import com.bluebeam.premierleaguego.data.service.RedditService
import com.google.common.base.Optional
import io.reactivex.Single
import net.dean.jraw.models.CommentSort
import net.dean.jraw.models.Submission
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
import javax.annotation.Nullable
/**
* Implementation of the [SubmissionRepository] interface. Stores [SubmissionWrapper]s in a map
* keyed by their id.
* TODO: should there be a limit to how many submissions are cached?
*/
@Singleton
class SubmissionRepositoryImpl
@Inject constructor(
val redditAuthentication: RedditAuthentication,
val redditService: RedditService) : SubmissionRepository {
private val idToSubmissionMap = HashMap<String, SubmissionWrapper>()
override fun getSubmission(
id: String,
sort: CommentSort,
forceReload: Boolean): Single<SubmissionWrapper> {
// Use submission in cache if available and has the right comment sorting.
if (!forceReload && idToSubmissionMap[id] != null && idToSubmissionMap[id]?.sort == sort) {
return Single.just(idToSubmissionMap[id])
}
return redditService.getSubmission(redditAuthentication.redditClient, id, sort)
.flatMap { s: Submission ->
val wrapper = SubmissionWrapper(s)
wrapper.sort = sort
idToSubmissionMap[wrapper.id] = wrapper
Single.just(wrapper)
}
}
override fun getCachedSubmission(id: String): Optional<Submission> {
val submission = idToSubmissionMap[id]?.submission
return Optional.of(submission)
}
override fun saveSubmission(submissionWrapper: SubmissionWrapper) {
idToSubmissionMap[submissionWrapper.id] = submissionWrapper
}
override fun reset() = idToSubmissionMap.clear()
}
我继续从getCachedSubmission函数获取的错误是: 预期类型不接受Java中的空值,但在Kotlin中该值可能为null。如果有任何关于如何解决此问题的建议会有所帮助。谢谢!
答案 0 :(得分:2)
Optional.of
不接受null
(如果获得例外,它会抛出异常),但使用?.
表示submission
可以是null
}。请改用Optional.ofNullable
。
答案 1 :(得分:0)
使用变量数据类型旁边的?
允许它接受空值。如果变量为if
,则在getCachedSubmission
函数(也有?
)中有一个null
语句来控制信息流。
在此示例中,我创建了argument
类型String?
的变量,以便稍后将其更改为null。在try / catch块中(我将其作为额外的异常处理层以防万一)我将一个参数传递给getCachedSubmission
,并且在函数内处理信息以改变传递的参数是什么{ {1}}。
要查看传递的参数为null
时发生的情况,请取消注释null
代码行。
argument = null;
希望这有帮助。