Created
August 21, 2022 11:43
-
-
Save dvt32/01c622e9d207a3e3025bdf13e58da18e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LambdaGoodies { | |
// When the lambda expression has only one param, we use "it" to access it | |
fun method1() { | |
val ints = listOf(0, 1, 2, 3).filter { // note that we use CURLY braces | |
it > 1 | |
} | |
ints.forEach { println(it) } | |
} | |
// We don't use stream() or collect() in Kotlin | |
fun method2() { | |
val people = listOf( Person("John"), Person("Mary") ) | |
val list = people.map { it.name } // Java: people.stream().map(Person::getName).collect(Collectors.toList()); | |
} | |
private data class Person(val name: String) | |
// Lambdas & functional programming in Kotlin can simplify some common operations | |
fun method3() { | |
// Example #1: sorting with custom comparator | |
val list = arrayListOf("asdf,", "a", "b") | |
Collections.sort(list, object : Comparator<String> { | |
override fun compare(o1: String?, o2: String?): Int { TODO("Not yet implemented") } | |
}) | |
Collections.sort(list, Comparator<String>( { o1, o2 -> TODO("Not yet implemented") } )) | |
Collections.sort(list, Comparator<String> { o1, o2 -> TODO("Not yet implemented") } ) | |
Collections.sort(list, Comparator { o1, o2 -> TODO("Not yet implemented") } ) | |
Collections.sort(list) { o1, o2 -> TODO("Not yet implemented") } // simplest | |
list.sortWith( Comparator({ o1, o2 -> TODO("Not yet implemented") }) ) | |
list.sortWith( Comparator { o1, o2 -> TODO("Not yet implemented") } ) | |
list.sortWith({ o1, o2 -> TODO("Not yet implemented") }) | |
list.sortWith { o1, o2 -> TODO("Not yet implemented") } // simplest | |
// Example #2: modifying several fields' values at once with "apply" | |
val user = User("John", "Doe", "USA") | |
user.apply { | |
firstName = "Ivan" | |
lastName = "Ivanov" | |
country = "Bulgaria" | |
} | |
} | |
private data class User(var firstName: String, var lastName: String, var country: String) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment