Issue
How can I create a Array like we do in java?
int A[] = new int[N];
How can I do this in Kotlin?
Solution
According to the reference, arrays are created in the following way:
For Java's primitive types there are distinct types
IntArray,DoubleArrayetc. which store unboxed values.They are created with the corresponding constructors and factory functions:
val arrayOfZeros = IntArray(size) //equivalent in Java: new int[size] val numbersFromOne = IntArray(size) { it + 1 } val myInts = intArrayOf(1, 1, 2, 3, 5, 8, 13, 21)The first one is simillar to that in Java, it just creates a primitive array filled with the default value, e.g. zero for
Int,falseforBoolean.Non primitive-arrays are represented by
Array<T>class, whereTis the items type.Tcan still be one of types primitive in Java (Int,Boolean,...), but the values inside will be boxed equivalently to Java'sInteger,Doubleand so on.Also,
Tcan be both nullable and non-null likeStringandString?.These are created in a similar way:
val nulls = arrayOfNulls<String>(size) //equivalent in Java: new String[size] val strings = Array(size) { "n = $it" } val myStrings = arrayOf("foo", "bar", "baz") val boxedInts = arrayOfNulls<Int>(size) //equivalent in Java: new Integer[size] val boxedZeros = Array(size) { 0 }
Answered By - hotkey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.