I am confused about java.lang.String and jet.String

I am confused about the difference and interoperability of java.lang.String and jet.String.

Here is a specific issue that I hit this morning… I have a Java class with a getName() method that returns java.lang.String. I have a Kotlin function:

public fun pushNode(name: String, value: Any): Unit {

}

When I try to call pushNode(javaObject.getName(), …)

The compiler gives the message:

“None of the following functions can be called with the arguments supplied”

and the list include:

pushNode(jet.String, jet.Any?)

So I am trying to call a method with java.lang.String when the Kotlin method defines jet.String as the argument type.

Would someone mind explaining the difference between jet.String, java.lang.String, and the rules for interoperability?

Thank you!

Randy

Are you sure it's not because getName() returns String? and not String (not nullable)? There seems to be an inconsistency between how you defined pushNode (second arg is Any) and what you are seeing the list (second arg is Any?)

Thank you!

That was the issue.

Randy

It is a good rule of thumb to assume that everything that comes java library's methods as nullable (unless it is already annotated otherwise)

Most of the "incorrect type" errors I have encountered writing Kotlin code were coming from the incompatibility between `Type?` and `Type`. It takes a little while to get used to but it's worth the trouble.

I am starting to get a "sense" of what you are saying - Type v Type? Thank you.

What I do not yet understand is what is jet.String? Again, newbie here… Is jet.String a class? If it is, what is the relationship to java.lang.String. If I’m stumbling on this then others coming to Kotlin may also - so maybe a discussion should be added to the documentation about this.

Thank you to everyone who is helping me on my Kotlin journey.

Regards,

Randy

Yes, jet.String is a class http://jetbrains.github.io/kotlin/versions/snapshot/apidocs/jet/String.html

jet.String is Kotlin built in string. It’s not the same as java.lang.String but it can be casted to jet.String and vice versa.

fun main(args : Array<String>) {   val s : java.lang.String = java.lang.String("hello")   val s2 : jet.String = s as jet.String      //val s3 : java.lang.String = "This won't work"     val s4 : jet.String = "This works"   val s5 : String = "This works"   println("${s4 == s5}")   val s6 : java.lang.String = "Java String" as java.lang.String }

For interop with Java methods and classes, you simply use String(jet.String) everywhere without needing to cast.

The same principle apply to other Kotlin primitives such as Double, Float, Long, Int, Short, Byte, Char, and Boolean.