Kun*_*ito 3 type-inference variable-assignment type-mismatch assignment-operator kotlin
val var1: Any = "Carmelo Anthony"
当我执行以下操作时,我的印象是::class.simpleName返回对象的变量类型:
val var1Type = var1::class.simpleName
print(var1Type)
我得到了String,但没有得到Any
但当我这样做时
val var2: String = var1
我得到一个Type mismatch: inferred type is Any but String was expected
::class运算符有两种形式:
TypeName::class-返回静态类型KClass的对象 TypeName。variableName::class-它返回一个与, 的运行时类型KClass相对应的对象variableName,而不是 variableName的静态类型。(Kotlin 在其文档中将此称为“绑定类型”)。var1运行时类型为 ,String但静态类型为Any。
var1::class返回KClassfor String, not Any。var2,您不能从另一个静态类型为 的变量 ( )String进行赋值,因为可能具有完全不兼容的运行时类型与,例如一个物体。
var2var3Anyvar3 StringInputStream
fun main() {
val var1: Any = "Carmelo Anthony"
val var1Type = var1::class.simpleName
println("var1's type: " + var1Type) // <-- This will print the *runtime type* of `var1` (String), not its static type (which is `Any`, *not* `String`).
/*
val var2: String = var1 // <-- Fails beause `var1` is `Any`, and `Any` is "wider" than `String`, and narrowing conversions always considered unsafe in languages like Kotlin, Java, etc.
*/
val var2Unsafe: String = var1 as String; // <-- Doing this is unsafe because it will throw if `var1` is not a String.
val var2Safe : String? = var1 as? String; // <-- Doing this is safe because it `var2Safe` will be null if `var1` is not a String.
println(var2Unsafe)
println(var2Safe)
}
Run Code Online (Sandbox Code Playgroud)
如果您熟悉其他语言,那么这里有一个不完整的等效操作及其语法表:
| 科特林 | 爪哇 | JavaScript | C# | C++ | |
|---|---|---|---|---|---|
| 获取静态类型 | TypeName::class |
TypeName.class |
ConstructorName |
typeof(TypeName) |
typeid(TypeName) |
| 获取运行时类型 | variableName::class |
variableName.getClass() |
typeof variableName(内在)variableName.constructor(对象) |
variableName.GetType() |
typeid(variableName) |
| 从名称(字符串)获取类型 | Class.forName( typeName ).kotlin |
Class.forName( typeName ) |
eval( typeName )(永远不要这样做) |
||
| 静态定义的运行时类型检查 | variableName is TypeName |
variableName instanceof TypeName |
typeof variableName === 'typeName'(内在)或variableName instanceof ConstructorName(对象) |
variableName is TypeName |
|
| 运行时动态类型检查 | otherKClass.isInstance( variableName )或者otherKType.isSubtypeOf() |
otherClass.isAssignableFrom( variableName.getClass() ) |
otherType.IsAssignableFrom( variableName.GetType() ) |
||
| 不安全的缩小(又名沮丧) | val n: NarrowType = widerVar as NarrowType; |
NarrowType n = (NarrowType)widerVar; |
variableName as TypeName(仅限 TypeScript) |
NarrowType n = (NarrowType)widerVar; |
|
安全缩小(向下或null) |
val n: NarrowType? = widerVar as? NarrowType; |
NarrowType n? = widerVar as NarrowType; |
dynamic_cast<NarrowType>( widerVar ) |
||
| 有条件缩小范围 | variableName is TypeName |
func(x: unknown): x is TypeName保护函数(仅限 TypeScript) |
widerVar is TypeName n |
| 归档时间: |
|
| 查看次数: |
860 次 |
| 最近记录: |