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进行链式调用,可以优雅点吧

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