Various topics

Kotlin Operators

Description and examples of higher-order functions (operators):

1. Filter Operator (filter)

Use: To extract elements from a collection that satisfy a given condition.
Example: Filtering out even numbers from a list.


val numbers = listOf(1, 2, 3, 4, 5, 6)
val evenNumbers = numbers.filter { it % 2 == 0 }
// Output: evenNumbers = [2, 4, 6]
        

2. Map Operator (map)

Use: To transform each element of a collection into a new form.
Example: Converting a list of names to their corresponding lengths.


val names = listOf("Alice", "Bob", "Charlie")
val nameLengths = names.map { it.length }
// Output: nameLengths = [5, 3, 7]
        

3. Reduce Operator (reduce / fold)

Use: To accumulate values in a collection to a single result.
Example: Calculating the sum of all numbers in a list.


val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.reduce { acc, number -> acc + number }
// Output: sum = 15
        

4. FlatMap Operator (flatMap)

Use: To transform each element into a collection and then flatten the results.
Example: Extracting all unique characters from a list of words.


val words = listOf("hello", "world")
val uniqueChars = words.flatMap { it.toCharArray().toList() }.toSet()
// Output: uniqueChars = [h, e, l, o, w, r, d]
        

5. Any Operator (any)

Use: To check if at least one element in a collection satisfies a condition.
Example: Checking if any student in a list has passed the exam.


val students = listOf(Student("Alice", true), Student("Bob", false))
val anyPassed = students.any { it.passed }
// Output: anyPassed = true
        

6. All Operator (all)

Use: To check if all elements in a collection satisfy a condition.
Example: Verifying if all tasks in a to-do list are completed.


val tasks = listOf(Task("Write code", true), Task("Test app", true))
val allCompleted = tasks.all { it.completed }
// Output: allCompleted = true
        

7. None Operator (none)

Use: To check if no elements in a collection satisfy a condition.
Example: Confirming that no errors occurred during validation.


val errors = listOf(Error("404"), Error("500"))
val noErrors = errors.none { it.isCritical }
// Output: noErrors = false
        

8. Count Operator (count)

Use: To count the number of elements that satisfy a condition.
Example: Counting how many apples are in a shopping cart.


val cart = listOf("apple", "banana", "apple", "orange")
val appleCount = cart.count { it == "apple" }
// Output: appleCount = 2
        

9. Find Operator (find)

Use: To locate the first element that satisfies a condition.
Example: Finding the first available product in a list.


val products = listOf(Product("Apple", true), Product("Banana", false))
val availableProduct = products.find { it.available }
// Output: availableProduct = Product("Apple", true)
        

10. First and Last Operators (first, last)

Use: To get the first or last element of a list.
Example: Getting earliest and latest appointments.


val appointments = listOf(
    Appointment("Meeting 1", LocalDateTime.of(2023, 8, 21, 10, 0)),
    Appointment("Meeting 2", LocalDateTime.of(2023, 8, 21, 15, 0))
)
val earliest = appointments.first()
val latest = appointments.last()
// Output: Meeting 1, Meeting 2
        

11. Take Operator (take)

Use: To extract a specific number of elements from the beginning of a collection.


val feed = listOf("Post 1", "Post 2", "Post 3", "Post 4")
val firstTwo = feed.take(2)
// Output: ["Post 1", "Post 2"]
        

12. Drop Operator (drop)

Use: To remove a specific number of elements from the beginning of a collection.


val pages = listOf("Page 1", "Page 2", "Page 3", "Page 4")
val nextPage = pages.drop(2)
// Output: ["Page 3", "Page 4"]
        

13. Sorted Operator (sorted)

Use: To sort elements in a collection based on a criterion.


val products = listOf(
    Product("Apple", 1.0),
    Product("Banana", 0.75),
    Product("Orange", 1.5)
)
val sortedByPrice = products.sortedBy { it.price }
// Output: [Banana, Apple, Orange]
        

14. GroupBy Operator (groupBy)

Use: To group elements in a collection by key or property.


val employees = listOf(
    Employee("Alice", "HR"),
    Employee("Bob", "Engineering"),
    Employee("Charlie", "HR"),
    Employee("David", "Engineering")
)
val grouped = employees.groupBy { it.department }
// Output: {HR=[Alice, Charlie], Engineering=[Bob, David]}
        

15. Partition Operator (partition)

Use: To split a collection into two lists based on a condition.


val orders = listOf(
    Order("Order 1", true),
    Order("Order 2", false),
    Order("Order 3", true)
)
val (completed, pending) = orders.partition { it.completed }
// Output: completed = [Order 1, Order 3], pending = [Order 2]
        

16. Associate Operator (associate)

Use: To build a map from a collection.


val products = listOf(
    Product("Apple", 1.0),
    Product("Banana", 0.75),
    Product("Orange", 1.5)
)
val productMap = products.associate { it.name to it.price }
// Output: {Apple=1.0, Banana=0.75, Orange=1.5}
        

17. Zip Operator (zip)

Use: To combine two lists element-wise.


val students = listOf("Alice", "Bob", "Charlie")
val grades = listOf(85, 92, 78)
val pairs = students.zip(grades)
// Output: [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
        

18. Distinct Operator (distinct)

Use: To remove duplicates from a collection.


val emails = listOf("user@example.com", "admin@example.com", "user@example.com")
val unique = emails.distinct()
// Output: ["user@example.com", "admin@example.com"]
        

19. MaxBy / MinBy Operators (maxByOrNull, minByOrNull)

Use: To find the element with max or min property value.


val temps = listOf(
    TemperatureRecord("Morning", 20.5),
    TemperatureRecord("Afternoon", 25.0),
    TemperatureRecord("Evening", 18.5)
)
val hottest = temps.maxByOrNull { it.temperature }
val coldest = temps.minByOrNull { it.temperature }
// Output: Afternoon (25.0), Evening (18.5)
        

Basics

IDE: Integrated Development Environment...

API: Application Programming Interface...

SDK: Software Development Kit...

UI: User Interface...

UX: User Experience...

JSON: JavaScript Object Notation...

XML: Extensible Markup Language...

HTTP: Hypertext Transfer Protocol...

MVC: Model-View-Controller...

OOP: Object-Oriented Programming...

Advanced

ORM: Object-Relational Mapping...

REST: Representational State Transfer...

SQLite: Lightweight Embedded Database...

Dagger: Dependency Injection Framework...

Gradle: Build Automation Tool...

Flutter: Cross-platform UI Framework...

RxJava: Reactive Extensions for Java...

Retrofit: HTTP Client Library...

Push Notification: Real-time Message Delivery...

Core Data: Data Persistence Framework (iOS)...

Dagger Hilt: Dependency Injection Library (Android)...

GraphQL: Query Language for APIs...

CI/CD: Continuous Integration/Continuous Deployment...

Proguard/R8: Code Obfuscation and Shrinking...

Firebase Analytics: App Usage Tracking...

NDK: Native Development Kit...

MVVM: Model-View-ViewModel...

Reactive Programming: RxSwift, RxCocoa (iOS)...

Security Best Practices: Encryption, SSL Pinning...

Accessibility: Making Apps Inclusive...

MVI Model-View-Intent Example

Organizing an Android app based on the MVI pattern:


// Model
data class CounterViewState(val count: Int)

// View (Activity)
class CounterActivity : AppCompatActivity() {
    private val viewModel: CounterViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_counter)

        incrementButton.setOnClickListener {
            viewModel.processIntent(CounterIntent.Increment)
        }

        viewModel.state.observe(this) { state ->
            countTextView.text = state.count.toString()
        }
    }
}

// Intent
sealed class CounterIntent {
    object Increment : CounterIntent()
}

// ViewModel
class CounterViewModel : ViewModel() {
    private val _state = MutableLiveData()
    val state: LiveData = _state

    init {
        _state.value = CounterViewState(0)
    }

    fun processIntent(intent: CounterIntent) {
        when (intent) {
            is CounterIntent.Increment -> {
                val current = _state.value ?: CounterViewState(0)
                _state.value = current.copy(count = current.count + 1)
            }
        }
    }
}