Hello, I found this case with Stream.of() and mad...
# getting-started
Hello, I found this case with Stream.of() and made me curious: If I send the array variable It does not iterate the objects in the operations only the full array. Why does Kotlin behave differently with this case to Java?
Copy code
val numbers = arrayOf("1", "2")

Stream.of(numbers).forEach { println(it) } // Prints all Array
// Prints out the full array:
// [Ljava.lang.String;@2121f1bb

Stream.of("1", "2").forEach { println(it) }  // Prints each item
// Prints out every item:
// 1
// 2
That's not really different behavior, just different syntax. You can do
to get the save behavior as Java. You can read about it in the docs (look for where it talks about the spread operator).
In this case, the Kotlin syntax has an advantage. Since varargs in Java are just sugar for arrays, if a function takes a generic vararg and you give it an array, it isn't immediately clear if you want the contents of the array as variadic arguments, or if you just want one argument that happens to be an array, since both options resolve to the same syntax. This ambiguity does not exist in Kotlin, as there is different syntax for those two ideas.
👍 1
👍🏼 1
Copy code
val numbers = arrayOf("1", "2")
Stream.of("1", "2")  // results in Stream<String> with 2 elements
Stream.of(numbers)   // results in Stream<Array<String>> with 1 element
Stream.of(*numbers)  // results in Stream<String> with 2 elements by "spreading" numbers to the vararg
This ambiguity can cause some gotchas in Java:
Copy code
String[] numbers1 = {"1", "2"};
String[] numbers2 = {"3", "4"};
Stream.of(numbers1, numbers2);  // results in Stream<String[]> with 2 elements
Stream.of(numbers1);            // results in Stream<String> with 2 elements due to implicit spreading
Copy code
void count(Object... objs) {

count(null, null, null);  // prints 3
count(null, null);        // prints 2
count(null);              // throws NullPointerException
count();                  // prints 0
Not to mention issues with primitive type arrays. You can read more in this SO answer.
😨 1