Is it a good practice to use multiple nested let in Kotlin or should I introduce a local variable instead? Is there any overhead?

webView?.let { webview ->
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        webview.setLayerType(View.LAYER_TYPE_HARDWARE, null)
    } else {
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
    }

    webview.webViewClient = WebViewClient()

    webview.settings.let { settings ->
        settings.javaScriptEnabled = true
        settings.setSupportZoom(false)
        settings.builtInZoomControls = false
        settings.displayZoomControls = false
        settings.loadsImagesAutomatically = true
    }
}

推荐答案

Since let is inlined (see: what is inlining, also the official docs), its cost is the exact same as declaring the local variable yourself. If you're using it with a safe call, it also adds a null check, which you'd have to do manually as well.

因此,使用它基本上没有开销,只要代码对您来说足够清晰,就可以随意使用它.


For example, code like this:

webview.settings.let { settings ->
    settings.javaScriptEnabled = true
    settings.setSupportZoom(false)
}

... would roughly translate to bytecode equivalent to this Java code:

Settings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setSupportZoom(false);

Except settings would probably be called something generic like var10000, but that's besides the point. Point is that no function instances are created and no let function is called or anything like that, therefore no overhead.

For any future concerns, you can actually check this yourself by using the Kotlin plugin's bytecode viewer and decompiler.

Kotlin相关问答推荐

Spring Boot Bean验证器未触发

计算值的Elvis算子

在Kotlin中,我是否可以访问已知的WHEN子句值?

Spring Boot 3:为Kotlin中的TestRestTemplate配置读取超时

Kotlin-elvis算子don';不使用map.get()

Kotlin - 如何避免在密封类的 when() 语句中转换第二个变量

为什么这两个 Kotlin 协程函数不一样?

如何使用 Firebase 和 Kotlin 在文本 (Jetpack Compose) 中显示当前用户名?

在 Kotlin 中,如何绑定扩展方法以在接收器范围函数中工作

Jetpack Compose 中的连续重组

为什么在 Kotlin 中调用私有构造函数会导致错误为无法访问 是什么?

如何将glide显示的图像下载到设备存储中.Kotlin

OnClickListener 未在 ConstraintLayout 上触发

Spring webflux bean验证不起作用

kotlin 扩展属性的惰性初始化器中的这个引用

应用程序在使用 Google Play 服务时遇到问题

如何在特定条件下清除jetpack数据存储数据

类型不匹配推断类型为单位,但应为空

kotlin 委托有什么用?

spring.config.location 在 Spring Boot 2.0.0 M6 上不起作用