Convert String to Long in Kotlin with example
Let’s declare an array in Kotlin
val array = arrayOf("a", "b", "c", "d")
Print an array using the println function.
println(array)
It outputs
[Ljava.lang.String;@7cc355be
It is difficult to inspect the values of an array during debugging with this. Then, How to print my Kotlin array object without getting “type@hashcode”?
This tutorial explains how to print the array of elements to the console.
How to Print array elements in Kotlin with an example
Multiple ways to log an array of items in Kotlin
Use for loop
The for in
loop iterates each element in an array and prints element to the console using the println
function.
Itis a native and basic way of iterating each element in an array.
import java.util.Arrays
fun main() {
val array = arrayOf("a", "b", "c", "d")
for (item in array) {
println(item)
}
}
Output:
a
b
c
d
using to Arrays.toString method
Arrays
has an inbuilt toString
method that takes an array variable and prints the values.
It is an easy and way to print without iterating each element.
import java.util.Arrays
fun main() {
val array = arrayOf("a", "b", "c", "d")
println(Arrays.toString(array))
}
Output
[a, b, c, d]
Array joinToString method
The joinToString
method takes a separator,iterates each element, appends, and returns the string.
fun main() {
val array = arrayOf("a", "b", "c", "d")
println(array.joinToString(" "))
}
forEach method
forEach🔗 takes lambda expression. It iterates each element, applies a function, and calls the body inside it.
fun main() {
val array = arrayOf("a", "b", "c", "d")
// lambda expression
array.forEach { println(it) }
//using method reference syntax
array.forEach(System.out::print)
}
When the above program prints,
a
b
c
d
abcd
Array contentToString function
contentToString()
function prints the array elements. It prints the string representation of each element and displays it to console.
fun main() {
val array = arrayOf("a", "b", "c", "d")
println(array.contentToString())// [a, b, c, d]
}
How to Print Array of Strings or Integers
An array of strings or integers printed with the above approach.
Here is an example
fun main() {
val numbers = intArrayOf(11, 12, 13, 14, 15)
println(numbers.contentToString())
}
Outputs:
[11, 12, 13, 14, 15]