Deproblemify
Deproblemify

Reputation: 3430

Kotlin requires explicit cast to Object

I am trying to write a method in Kotlin that returns an object of type Object.

In Java I would simply write this as

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

However, in Kotlin this does not work and throws an error

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

When casting the string return "Bla" as Object it works. Interestingly, the Kotlin Object is imported from java.utils and is probably not the same Object as it is in the Java code.

Why is this so? Does Kotlin not want you to return such general objects? How would I go about achieving this in Kotlin?

Upvotes: 2

Views: 199

Answers (1)

Rene
Rene

Reputation: 6258

In Kotlin the type hierarchy starts with Any: https://kotlinlang.org/docs/reference/classes.html#inheritance

You could write:

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

But Any isn't 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.

Upvotes: 4

Related Questions