We Are Going To Discuss About What’s the Kotlin equivalent of Java’s String[]?. So lets Start this Java Article.
What’s the Kotlin equivalent of Java’s String[]?
- What's the Kotlin equivalent of Java's String[]?
To create an empty Array of Strings in Kotlin you should use one of the following six approaches:
First approach:val empty = arrayOf<String>()
Second approach:val empty = arrayOf("","","")
- What's the Kotlin equivalent of Java's String[]?
To create an empty Array of Strings in Kotlin you should use one of the following six approaches:
First approach:val empty = arrayOf<String>()
Second approach:val empty = arrayOf("","","")
Solution 1
There’s no special case for String
, because String
is an ordinary referential type on JVM, in contrast with Java primitives (int
, double
, …) — storing them in a reference Array<T>
requires boxing them into objects like Integer
and Double
. The purpose of specialized arrays like IntArray
in Kotlin is to store non-boxed primitives, getting rid of boxing and unboxing overhead (the same as Java int[]
instead of Integer[]
).
You can use Array<String>
(and Array<String?>
for nullables), which is equivalent to String[]
in Java:
val stringsOrNulls = arrayOfNulls<String>(10) // returns Array<String?>
val someStrings = Array<String>(5) { "it = $it" }
val otherStrings = arrayOf("a", "b", "c")
See also: Arrays in the language reference
Original Author hotkey Of This Content
Solution 2
use arrayOf, arrayOfNulls, emptyArray
var colors_1: Array<String> = arrayOf("green", "red", "blue")
var colors_2: Array<String?> = arrayOfNulls(3)
var colors_3: Array<String> = emptyArray()
Original Author Dan Alboteanu Of This Content
Solution 3
To create an empty Array of Strings in Kotlin you should use one of the following six approaches:
First approach:
val empty = arrayOf<String>()
Second approach:
val empty = arrayOf("","","")
Third approach:
val empty = Array<String?>(3) { null }
Fourth approach:
val empty = arrayOfNulls<String>(3)
Fifth approach:
val empty = Array<String>(3) { "it = $it" }
Sixth approach:
val empty = Array<String>(0, { _ -> "" })
Original Author Andy Jazz Of This Content
Solution 4
Those types are there so that you can create arrays of the primitives, and not the boxed types. Since String isn’t a primitive in Java, you can just use Array<String>
in Kotlin as the equivalent of a Java String[]
.
Original Author zsmb13 Of This Content
Conclusion
So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.