
That way, your intention and the fact that you thought about nullability are explicit. Hence, I recommend stating the type explicitly when calling a Java method. This is unsafe if you don’t think about whether the method you’re calling does actually never return null. Without an explicit type, the compiler infers the non-nullable variant of the platform type so that you can use it without handling null. Val nullable: String? = hello() // Explicit type: String? Val str = hello() // Inferred type: String (by default) Looping as usual, ArrayList provides iterator()įor (item in arrayList) Val arrayList = ArrayList() // Uses ĪrrayList.addAll(arrayOf("Mercury", "Venus", "Jupiter"))ĪrrayList = arrayList // Indexed access operator calls ‘get’ and ‘set’ Listing 5.1 Using Java Libraries from Kotlin import .Stats In this section, we’ll explore the details and possible pitfalls, as well as how to write Kotlin-friendly Java code and how to improve your Java code to provide additional information for the Kotlin compiler, especially about nullability.įirst, it’s important to appreciate the fact that you can easily use the Java standard library and any third-party library in a natural way. Java code can be called from Kotlin in the way you would expect most of the time. In this chapter, you’ll learn the ins and outs of mixing Kotlin and Java, how their language concepts map to each other, what happens under the hood in the Kotlin compiler to aid interoperability, and how you can write code that further facilitates it.

Interoperability has been one of Kotlin’s priorities from its inception. Synergy is better than my way or your way.
