【问题标题】:Why is my null check unreachable?为什么我的空检查无法访问?
【发布时间】:2019-01-13 02:47:12
【问题描述】:

在以下示例中,我有一个可为空的属性 userId。如果它为空,我想抛出一个异常。 Android Studio 告诉我 if(userId == null) 内部的代码块无法访问。谁能解释为什么这是无法访问的?

return Observable.create<Optional<UserEntity>> { it ->

        val userId: String? = firebaseAuth.currentUser?.uid

        if(userId == null){
            it.onError(throw RuntimeException("Unauthorised"))
            it.onComplete()
        }else{
            //Do something
        }

    }

【问题讨论】:

  • 如果firebaseAuth 不可为空且currentUser 不可为空且uid 不可为空,它可能无法访问?对吗?

标签: android kotlin nullable unreachable-code


【解决方案1】:

好的...我明白了...实际上是以下行包含无法访问的代码:

it.onError(throw RuntimeException("Unauthorised"))

原因:您立即抛出异常,而不是在处理过程中发生错误时抛出。事实上,onError 本身变得无法访问。

onError 但是,需要将异常作为传递的参数抛出,所以您更想要的是:

it.onError(RuntimException("Unauthorised"))

即省略throw

【讨论】:

  • 对不起...这显然不是我的意图 ;-) 但我想我也已经这样做了...所以...它发生了 ;-)
猜你喜欢
  • 2015-01-11
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
相关资源
最近更新 更多