kotlin,使用"is"是更好的选择或“为?", [英] kotlin, which one is better, using "is" or "as?",

查看:97
本文介绍了kotlin,使用"is"是更好的选择或“为?",的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个函数test1和test2,一个使用"is"检查类型,一个使用"as?",似乎test2带有"as?"的代码更少,但是真的比使用是"进行检查的代码好吗?

two functions test1 and test2, one uses "is" to check type, and one use "as?", seems test2 with "as?" has less code, but is it really better than the one uses "is" to do check?

是否使用"is"和"as"进行比较,这两个的一般用法有什么建议?

Is there a comparison for using "is" vs. "as?", what is suggestion for general use of these two?

class Message(val int: Int, val msg:String)
class Test {
    fun test1(objList: List<Any?>) {
        for (i in objList.size - 1 downTo 0) {
            val item = objList.get(i)
            if (item is Message) {
                println(item)
            }
        }
    }

    fun test2(objList: List<Any?>) {
        for (i in objList.size - 1 downTo 0) {
            (objList.get(i) as? Message)?.let {item ->
                println(item)
            }
        }
    }
}

推荐答案

因此,如果您查看两者的JVM字节码:

So if you look at the JVM bytecode of both:

// JVM bytecode of test1
   L5
    LINENUMBER 8 L5
    ALOAD 3
    INSTANCEOF com/example/artifact/Message
    IFEQ L6

// JVM bytecode of test2
   L4
    LINENUMBER 16 L4
    ALOAD 0
    ILOAD 1
    INVOKEINTERFACE java/util/List.get (I)Ljava/lang/Object; (itf)
    DUP
    INSTANCEOF com/example/artifact/Message
    IFNE L5
    POP
    ACONST_NULL
   L5
    CHECKCAST com/example/artifact/Message
    DUP
    IFNULL L6
    ASTORE 3

您可以清楚地看到test1仅检查类型,并且智能地转换结果,而test2但是首先检查实例是否属于该类型,然后显式返回null或"casts"这种类型.

You can clearly see that the test1 does check for the type only and it smart casts the result, while the test2 however first checks if the instance is of that type and then returns null or "casts" explicitly it to that type.

因此,通过此观察,我建议您使用is运算符,因为它针对这些任务进行了优化.如果您不喜欢使用花括号,则可以像python一样省略它们,或者在有条件的情况下将println放在与您执行的操作相同的行上.

So, through this observation I'll suggest you to use the is operator as it is more optimized for these tasks. If you don't like using curly braces then you can omit them like python, or put the println on the same line as you're doing if conditions.

如果您愿意,这是更优化的代码:

This is more optimized code if you'd like:

fun test1(objList: List<Any>) {
    for (item in objList.asReversed()) {
        if (item is Message) println(item)
    }
}

fun test2(objList: List<Any>) {
    for (item in objList.asReversed()) {
        (item as? Message)?.let { println(it) }
    }
}

这篇关于kotlin,使用"is"是更好的选择或“为?",的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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