Null Safety
See https://kotlinlang.org/docs/reference/null-safety.html
?.let
To perform a certain operation only for non-null values, you can use the safe call operator together with let
:
case1:
//Java:
private void updateView(ArticlesUiModel uiModel) {
if (uiModel == null) {
return;
}
// update view
}
//Kotlin:
private fun updateView(uiModel: ArticlesUiModel?) {
uiModel?.let {
// update view
}
}
case2:
Only safe(?.) or non-null asserted(!!.) calls are allowed on a nullable receiver of type Boolean?
return if (element != null && !element.isJsonNull) element.asString else null
null cannot be a value of non-null type
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Article? {
if (TextUtils.isEmpty(title) && TextUtils.isEmpty(description) && TextUtils.isEmpty(imageHref)) {
return null // 如果需要返回null,返回类型必须后缀 ?
}
return Article(title, description, imageHref)
}