Using the 'distinctBy' Function for Unique Collection Elements

The 'distinctBy' function in Kotlin allows you to filter a collection to contain only unique elements based on a specified selector. This is particularly useful when you want to remove duplicates from a list while keeping the first occurrence of each unique element. It can make your code cleaner and more efficient by avoiding manual iterations and checks for uniqueness.

val items = listOf("apple", "banana", "apple", "orange", "banana", "kiwi")
val distinctItems = items.distinctBy { it }
println(distinctItems) // Output: [apple, banana, orange, kiwi]