Reputation: 1949
I am new to kotlin with Android Studio. I have written a function in kotlin which accepts an Arraylist as input and randomly shuffles it -
fun randomize(array: ArrayList<Any>) { ... }
I want this function to accept ArrayList of any type but calling with following arguments gives type mismatch error -
val arr = ArrayList<Int>()
// ...
randomize(array = arr) // Gives Error
How can I use ArrayList that accepts any type. Thanks for your help.
Upvotes: 2
Views: 2198
Reputation: 89608
You need to make your function generic, like so:
fun <T> randomize(array: ArrayList<T>) {
// do whatever you want to your `ArrayList`
}
But if you don't have any specific way in mind for how to do the shuffling, you can just use the shuffle
method of the standard library:
val arr = ArrayList<Int>()
// ...
arr.shuffle()
Upvotes: 5