Array based Kotlin interview questions and answers
How to Create Arrays of Different Types in Kotlin
Kotlin allows programmers to easily create different types of arrays using the arrayOf() method. Below, we’ll take a look at how to create arrays containing integer, floats, and strings using this simple but robust procedure.
val arr1 = arrayOf(1, 2, 3) val arr2 = arrayOf(1.2, 2.3, 3.4) val arr3 = arrayOf("Hello", "String", "Array)
How to initialize an array in Kotlin with values? How to initialize an array in Kotlin with values?
In Java an array can be initialized such as:
int numbers[] = new int[] {10, 20, 30, 40, 50}
How does Kotlin's array initialization look like?
val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
May you use IntArray and an Array<Int> is in Kotlin interchangeably? May you use IntArray and an Array<Int> is in Kotlin interchangeably?
Array<Int>
is an Integer[]
under the hood, while IntArray
is an int[]
.
This means that when you put an Int
in an Array<Int>
, it will always be boxed (specifically, with an Integer.valueOf()
call). In the case of IntArray
, no boxing will occur, because it translates to a Java primitive array.
So no, we can't use them interchangeably.
What is the idiomatic way to remove duplicate strings from array? ☆☆
Details: How to remove duplicates from an Array<String?>
in Kotlin?
Answer: Use the distinct
extension function:
val a = arrayOf("a", "a", "b", "c", "c")
val b = a.distinct() // ["a", "b", "c"]
You can also use:
toSet
,toMutableSet
toHashSet
- if you don't need the original ordering to be preserved
These functions produce a Set
instead of a List
and should be a little bit more efficient than distinct.
May you use IntArray and an Array is in Kotlin interchangeably? ☆☆☆
Answer: Array<Int>
is an Integer[]
under the hood, while IntArray
is an int[]
.
This means that when you put an Int
in an Array<Int>
, it will always be boxed (specifically, with an Integer.valueOf()
call). In the case of IntArray
, no boxing will occur, because it translates to a Java primitive array.
So no, we can't use them interchangeably.
Source: stackoverflow.com
Comments
Post a Comment