
But that’s a relatively minor expense.Īnd cool features can be quite handy when you’re writing fresh code.īut when you come to debug your code, to work out what on earth the compiler’s complaining about or why it does something unexpected when run, each extra feature can multiply the amount of head-scratching and cursing. And I’ve hated them.įor one thing, each extra feature makes the language that bit longer and harder to learn. This effectively means that if we pass in T we get out an array Array.I’ve used kitchen-sink languages, where every pet feature got thrown in. If we dig deep into Kotlin Standard Library, the function arrayOf() is actually returning Array where T is the type of the elements in the array. Now, let’s look at 2D array initialization and usage examples in kotlin! 2D Arrays in KotlinĢD arrays are a convenient way to store grid/board/matrix type of data. Mutable lists provide a lot more functions: get(), set(), plus, minus(), etc. indices ) // You can also use listOrArray to access the element at the given index. The below code works for both lists and arrays for ( i in listOrArray. Here are examples to declare a type-safe mutable lists with various examples: MutableListOf() allows us to manually define type-safe lists. If you pass in multiple data types in the constructor, the list will automatically be of type Any. To explicitly allow for it, use mutableListOf() to add mixed data types to the list. Note: Unlike arrayOf(), once mutableListOf() automatically infers a single data type, you can’t change the data type of the list. Using them, we can add, remove, or modify the elements in the list without re-creating it! It works similar to arrayOf(), but provides us functions to perform actions on the list. 1D arrays with dynamic sizeįor lists of dynamic size, we use the function mutableListOf(). Kotlin standard library supports for functions like intArrayOf(), doubleArrayOf(), booleanArrayOf(), etc. It is pretty useful if you want to store data that is strongly typed. Type mismatch: inferred type is String but Int was expected
