You can directly write the array in modern Java, without an initializer. Your example is now valid. It is generally best to name the parameter anyway.
String[] array = {"blah", "hey", "yo"};
or
int[] array = {1, 2, 3};
If you have to inline, you'll need to declare the type:
functionCall(new String[]{"blah", "hey", "yo"});
or use varargs (variable arguments)
void functionCall(String...stringArray) {
// Becomes a String[] containing any number of items or empty
}
functionCall("blah", "hey", "yo");
Hopefully Java's developers will allow implicit initialization in the future
Kotlin has made working with arrays so much easier! For most types, just use arrayOf
and it will implicitly determine type. Pass nothing to leave them empty.
arrayOf("1", "2", "3") // String
arrayOf(1, 2, 3) // Int
arrayOf(1, 2, "foo") // Any
arrayOf<Int>(1, 2, 3) // Set explict type
arrayOf<String>() // Empty String array
Primitives have utility functions. Pass nothing to leave them empty.
intArrayOf(1, 2, 3)
charArrayOf()
booleanArrayOf()
longArrayOf()
shortArrayOf()
byteArrayOf()
If you already have a Collection
and wish to convert it to an array inline, simply use:
collection.toTypedArray()
If you need to coerce an array type, use:
array.toIntArray()
array.toLongArray()
array.toCharArray()
...