Kotlin null safe實戰的風騷走位

如何正確使用 ?. ?: 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進行鏈式調用,可以優雅點吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章