如何正確使用 ?. ?: let
來避免空指針,並簡化書寫
Java的錯誤示例
//***
private WeakReference<TextureView> textureViewReference;
@Override
public int getWidth() {
return textureViewReference.get().getWidth();
}
@Override
public void setPreviewDisplay(Camera camera) throws IOException {
camera.setPreviewTexture(textureViewReference.get().getSurfaceTexture()); //設置預覽Holder
}
WeakReference可能返回null
java null safe版本
public int getWidth() {
View view = textureViewReference.get();
return view == null? view.getWidth() : 0; // 用 if else 更吐
}
public void setPreviewDisplay(Camera camera) throws IOException {
View view = textureViewReference.get();
if (view != null ) {
camera.setPreviewTexture(view.getSurfaceTexture()); //設置預覽Holder
//view.***
}
}
Kotlin safe 版本
public int getWidth() {
return textureViewReference.get()?.getWidth()?:0
}
public void setPreviewDisplay(Camera camera) throws IOException {
textureViewReference.get()?.let {
camera.setPreviewTexture(it.getSurfaceTexture()); //設置預覽Holder
//it.***
}
}
用法
result = a?.b()
if (a == null) {
result = null;
} else {
result.b()
}
result = c?:d
if ( c != null) {
result = c;
} else {
result = d;
}
let, run, also, apply, with
區別就是 形參、返回值
// 9
result = 3.let{it + 2}.let{it + 4}
關鍵字後面跟的是lambda,it是形參。
let, run 返回閉包的 結果
also, apply 返回 調用方法的變量
apply, run在閉包內默認 this 等於調用方
also, let 需要用it
總結
用 ?: ?. let run also apply with
進行鏈式調用,可以優雅點吧