gpt4 book ai didi

kotlin - Kotlin需要显式转换为Object

转载 作者:行者123 更新时间:2023-12-02 12:38:58 26 4
gpt4 key购买 nike

我正在尝试在Kotlin中编写一个返回Object类型的对象的方法。

在Java中,我只需将其写为

public Object test() {
return "Bla";
}

但是,在Kotlin中,此操作无效并引发错误
fun test(): Object {
return "Bla"
}

当转换字符串 return "Bla" as Object时,它可以工作。有趣的是,Kotlin Object是从 java.utils导入的,可能与Java代码中的Object不同。

为什么会这样呢? Kotlin不想让您返回此类通用对象吗?我将如何在Kotlin实现这一目标?

最佳答案

在Kotlin中,类型层次结构以Any开头:https://kotlinlang.org/docs/reference/classes.html#inheritance

您可以这样写:

fun test() : Any {
return "Bla"
}

但是 Any不是 Object

Note: Any is not java.lang.Object; in particular, it does not have any members other than equals(), hashCode() and toString(). Please consult the Java interoperability section for more details.

关于kotlin - Kotlin需要显式转换为Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52890498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com