我想要实现的是从函数中获取
Any!
返回类型,这样我就可以自己决定是否处理可空性。我发现获得这种类型的唯一方法是调用 Java 函数。
例如:
public static Integer getInt(JsonObject json, String key) {
return json.get(key).getAsInt();
}
这样我就可以在 Kotlin 中将它用作 Nullable 或 Non-nullable 类型。
getInt(json, "id") ?: 0
或getInt(json, "id")
。 Kotlin 编译器不会抱怨可空性,因为返回类型是 Int!
。
有没有什么方法可以在 Kotlin 中创建这样的返回类型而不使用 Java?
附注我真的不想在 Kotlin 中创建两个函数,例如
getInt(...)
和 getIntOrNull(...)
。