“ as”与“ as”之间的区别是什么?和“是” Kotlin的运营商? [英] What is difference between "as" and "is" operator in Kotlin?

查看:333
本文介绍了“ as”与“ as”之间的区别是什么?和“是” Kotlin的运营商?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我可以编写如下代码:

In Java, I can write code like:

    void cast(A a)  {
    if(a  instanceof  Person)  {
        Person p = (Person) a;
    }
}

在科特林,我该怎么办?
使用作为运算符还是运算符?

In Kotlin, what should I do? Use as operator or is operator?

推荐答案

是X 等效于 instanceof X

foo as X 等效于((X)foo)

此外,Kotlin会在可能的情况下执行智能投射,因此在使用检查类型之后,无需进行其他投射:

Additionally, Kotlin performs smart casting where possible, so no additional cast needed after you check the type using is:

open class Person : A() {
    val foo: Int = 42
}

open class A

然后:

if (p is Person) {
    println(p.foo) // look, no cast needed to access `foo`
}

这篇关于“ as”与“ as”之间的区别是什么?和“是” Kotlin的运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆