Explain Codes LogoExplain Codes Logo

What's the Kotlin equivalent of Java's String

kotlin
nullable
performance
type-safety
Anton ShumikhinbyAnton Shumikhin·Oct 3, 2024
TLDR

In Kotlin, replace Java's String[] with Array<String>. Initialize it like this:

val words = arrayOf("alpha", "beta", "gamma")

Or, when initializing with a specific size and indices:

val indexedWords = Array(3) { i -> "Word$i" } // Easy as 0, 1, 2!

We use arrayOf to create an array with elements, whereas Array(size) { } allows for element creation based on an index.

Understanding nullable and non-nullable strings in Kotlin

Kotlin provides more options and safety with nullable string arrays and specialized primitive type arrays.

Dealing with nullables

For an array capable of holding null values:

val maybeWords = arrayOfNulls<String>(3)

Or use this to initialize with null:

val maybeWords = Array<String?>(3) { null } // It's okay, not every slot has to hold a word!

Special array types for primitives

For performance optimization, Kotlin has specialized array types like IntArray, ByteArray etc., similar to Java's int[], byte[], etc.

val numbers = intArrayOf(42, 7, 100) // Because we love random numbers!

Empty arrays – Yes, they exist!

Create an empty array with emptyArray<T>() or simply initialize an array with a size of 0.

val emptyWords: Array<String> = emptyArray() val emptyMaybeWords: Array<String?> = arrayOfNulls(0) // Much ado about nothing!

Wrapping up with advanced initialization

You can dynamically generate array values during initialization, making use of index-based logic:

val prefixedWords = Array(3) { i -> "Word number ${i+1}" } // Numbered for your convenience!

Everything else you should know about Kotlin arrays

Kotlin expands your toolbox with more array capabilities, from expressive initializations to char arrays and type conversions.

Crafting the array with logic

In Kotlin, array initialization can include nifty logic, thanks to the power of lambdas:

val greetings = Array(3) { index -> when(index) { 0 -> "Hello" // English 1 -> "Bonjour" // French 2 -> "Hola" // Spanish else -> "Hi" // If all else fails, keep it simple! }}

Dealing with chars in arrays

For character arrays, Kotlin recommends charArrayOf() rather than Array<Char>:

val abc = charArrayOf('a', 'b', 'c') // Learning the ABCs the Kotlin way!

Changing array types

Kotlin provides seamless conversion between array types, ensuring your code is as flexible as it can be:

val wrappedInts: Array<Int> = arrayOf(1, 2, 3) val primitiveInts: IntArray = wrappedInts.toIntArray() // Unwrapping presents!

FAQs: Everything else we wondered about Kotlin arrays

Non-empty array of nulls: Is it possible?

Yes! To create a non-empty array containing only null values:

val arrayOfNulls: Array<String?> = Array(5) { null } // All dressed up with nowhere to go!

Are there performance benefits?

When should I pick specialized primitive arrays like IntArray over Array<Int>? Whenever you want to save time and memory by avoiding overhead of boxing.

And what about type safety?

Can Kotlin's typed arrays help avoid ClassCastException? Yes, Kotlin's stricter type system traps type errors at compile-time, not at runtime. Fewer runtime exceptions, yay!