如何正确使用 ?. ?: 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
区别就是 形参、返回值 和 闭包内this是谁
// 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
进行链式调用,可以优雅点吧
注意 return
- 如果闭包存在嵌套,return将直接返回最外层的闭包。
- return指定层,要用标签
public Future<?> submit(Runnable r) {
return executor.submit(r);
}
fun testReturn() {
//***
submit {
bitmap = FrameManager.frameManager?.let handle@{frameManager ->
if (frameManager.isInit()) {
val result = bitmap?.let { frameManager.mGraphicManager?.handleFrame(it) }
return@handle result?.handledBitmap?:bitmap
} else {
return@handle bitmap
}
}
}
//***
}