Kotlin调用Java平台类型导致llegalStateException

时间:2017-07-16 10:00:22

标签: android exception kotlin stack-trace

我在我的某个Android课程中使用kotlin,当我试图从IllegalStateException获取额外费用时,有时会弹出Bundle keyOrTag = bundle.getString("tag")

val

val keyOrTag: String 被声明为

{{1}}

不幸的是,我没有完整的堆栈跟踪,因为我已经从GP控制台注意到了这一点。

2 个答案:

答案 0 :(得分:4)

好的,我相信我知道为什么会这样。将其作为答案发布,以便其他有相关问题的人可以看到。

添加到捆绑包中的... // Acquire connection from pool. (Database query) // Release connection to pool. (Non-database-related code) // Acquire connection from pool. (Database query) // Release connection to pool. ... 实际上可以是Java类中的String "tag",它将其发送到null。由于我没有声明Kotlin可以为空,我相信这就是为什么它会抛出IllegalStateException(是的,kotlin中没有NPE)。

修复:

val

答案 1 :(得分:3)

  

何时发生此错误?

当您调用Java平台类型时,Kotlin kotlin.jvm.internal.Intrinsics可能会抛出IllegalStateException

  

为什么您是否看不到来自Kotlin kotlin.jvm.internal.IntrinsicsException投掷的stackTrace?

这是因为Kotlin在Intrinsics#sanitizeStackTrace方法内部删除了stackTrace

private static <T extends Throwable> T sanitizeStackTrace(T throwable) {
    return sanitizeStackTrace(throwable, Intrinsics.class.getName());
}

实施例

以下是Java平台类型StringUtils源代码,如果参数toNullnull或{{1},则value方法将返回null }}

""

然后您尝试将方法调用的结果分配给不可为空的变量,可能会抛出public class StringUtils { public static String toNull(String value) { return value == null || value.isEmpty() ? null : value; } } ,例如:

IllegalStateException
  

如何避免kotlin.jvm.internal.Intrinsics引发此类异常?

IF 您不确定返回值是否为val value: String = StringUtils.toNull("") // ^ //throws IllegalStateException: StringUtils.toNull("") must not be null //try to assign a `null` from `toNull("")` to the non-nullable variable `value` 来自Java平台类型,您应该将值分配给可以为空的变量/使返回类型可以为空,例如:

null