What is the difference between

x as? String

and

x as String?

它们看起来都是String?型的.Kotlin page不能帮我接听.

更新:

To clarify, my question is:

What is the purpose of having an as? operator at all, since for any object x and for any type T, the expression x as? T can be (I think) rephrased as x as T? ?

推荐答案

The difference lies in when x is a different type:

val x: Int = 1

x as String? // Causes ClassCastException, cannot assign Int to String?

x as? String // Returns null, since x is not a String type.

Kotlin相关问答推荐

如何在使用Kotlin Coroutines时检测和记录何时出现背压

计算值的Elvis算子

Microronaut Data 4和JDbi

Kotlin中一个接口的实现问题

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

哪个更好? Integer.valueOf(readLine()) 或 readLine()!!.toInt()

在 Compose 中使用 Text() 时如何获取文本的大小?

如何在 jOOQ 中两次加入同一张表?

多个不同的指针输入

Kotlin 具体类从抽象类和接口扩展而来,接口使用抽象类中实现的方法

如何在 Compose 中创建可重用的修饰符?

如何从 kotlin 中的数据类访问 val?

Kotlin 可打包类抛出 ClassNotFoundException

如何在 Kotlin for Android 上使用setTextColor(hexaValue),

如何使用 Findbugs 避免 kotlin 文件

使用 Hilt 注入 CoroutineWorker

Kotlin 是如何编译的?

Kotlin如何分派invoke操作符?

如何根据ArrayList的对象属性值从中获取最小/最大值?

将字符串转换为HashMap的最简单方法