You're reading for free via Android Dev Nexus' Friend Link. Become a member to access the best of Medium.

Member-only story

Kotlin Cheat Sheet for Android Developers 🚀

Android Dev Nexus
8 min readSep 27, 2024

Developers Assemble! 🗿

Hello you genius developers, welcome to yet another part of our ongoing Kotlin series where we’ll be covering the essentials you’ll use daily to create fantastic apps 🤗

Let’s explore the cheat sheet, then!

🌟Members can scroll down to enjoy! Non-members, click here for full access.🌟

1. val vs var 🤧

  • val: Immutable reference (like final in Java). You cannot reassign a value once assigned.
  • var: Mutable reference. The value can change during runtime.

2. lateinit ⏰

  • What: Allows initializing a non-null variable later, typically for dependency injection or unit testing.
  • Why: Used when you cannot initialize a variable at the time of declaration, often for classes or Android views.
  • Use case: Fragment fields injected by frameworks.

⭐️ Note: lateinit only works with var and non-primitive types ⭐️

3. lazy 😴

  • What: Lazily initializes a value when it is first accessed.
  • Why: Useful for expensive operations or objects that shouldn’t be initialized until necessary (e.g., a large resource, a heavy computation).

4. Nullable Types and Safe Calls 😷

  • What: Types that can hold null values, denoted by ?. Safe calls (?.) prevent NullPointerException.
  • Why: Enhances null safety, reducing runtime crashes due to null references.

⭐️ Tip: Use the Elvis operator (?:) to provide default values ⭐️

5. Scope Functions (let, apply, run, also, with) 🐼

  • What: Functions that allow executing a block of code within the context of an object.
  • Why: Improves code readability and reduces boilerplate by providing a concise way to work with objects.

6. Immutable Collections (listOf, mapOf, emptyListOf, emptyMapOf) 🌻

  • What: Immutable collections that cannot be modified after creation.
  • Why: They provide safety by ensuring your data remains unchanged.

7. Mutable Collections (mutableListOf, mutableMapOf) 🍄

  • What: Collections that allow modifications after creation.
  • Why: Useful when the data structure needs to change dynamically.

8. repeat, forEach, forEachIndexed 🔁

  • What: repeat — Repeats a block of code multiple times.
    forEach — Iterates over each element in a collection
    forEachIndexed — Iterates with both the index and the element.
  • Why: Clean and concise way to run a loop without a loop variable.

9. filter 🐚

  • What: Returns a list of elements that match a given condition.
  • Why: Useful when you need to pick only certain elements from a collection.

10. any 🍒

  • What: Returns true if at least one element in a collection matches a condition else false
  • Why: Useful for validation checks on collections

11. takeIf

  • What: Returns the object if it matches a condition, otherwise returns null.
  • Why: Handy for conditionally returning a value based on a predicate.

12. firstOrNull 🥇

  • What: Returns the first element of a collection that matches the given predicate, or null if none found.
  • Why: Helps avoid crashes when no matching element is found.

13. map {}

  • What: Transforms each element of a collection and returns a new collection.
  • Why: Great for transforming one type of collection to another or performing operations on each element.

14. flatMap {}

  • What: Transforms each element into a collection and flattens the result into a single list.
  • Why: Useful when you have a collection of collections, and you want to apply a transformation and flatten the result into a single list.

15. Transformations (transform) 🤖

  • What: Higher-order functions that transform collections.
  • Why: Helps to manipulate collections and make your code more functional and readable.

16. when 🤨⁉️

  • What: An alternative to the if-else or switch statements.
  • Why: Provides efficient branching based on multiple conditions.

⭐️ Tip: when can also be used without an argument for more complex branching ⭐️

17. static methods

  • What: Kotlin doesn’t have static methods like Java. Instead, you use companion objects to define functions tied to a class.
  • Why: Provides similar functionality to static in Java

18. Extension Functions 👮🏻

  • What: Allows adding new functions to existing classes without inheriting them.
  • Why: Enhances readability and allows for cleaner code by extending functionality without modifying original classes.

19. Higher-Order Functions 👮🏻🚨

  • What: Functions that take other functions as parameters or return them.
  • Why: Makes code more reusable.

20. Inline Function 📈

  • What: A function where the actual code of the function is copied into the call site at compile time i.e. instead of calling the function, the body of the function is inserted where the function is used.
  • Why: When you pass a function or lambda to another function, it usually creates extra objects. This can slow down performance.

Here, the logExecution function logs before and after the action, and because it's marked inline, the lambda action is directly inserted into the function call during compilation, removing the need for extra lambda object creation.

21. open 📖

  • What: Marks a class or function as extendable.
  • Why: In Kotlin, classes and methods are final by default. You need to mark them as open to allow inheritance.

22. data class 📊

  • What: Classes primarily used to hold data with automatically generated functions like equals(), hashCode(), and toString().
  • Why: Simplifies the creation of classes that are meant to store data without boilerplate code.

23. data class vs Regular Class

  • What: data class automatically provides equals(), hashCode(), toString(), and copy() methods.
  • Why: Reduces boilerplate code for classes that are primarily used to store data.

⭐️ Tip: For a better understanding of data classes, we’d recommend going through the following blog: https://medium.com/@android-dev-nexus/kotlin-class-essentials-part-1-data-classes-5b8861275697 ⭐️

24. sealed class 🔏

  • What: Restricts class hierarchies, allowing only a limited set of subclasses.
  • Why: Useful for representing restricted class hierarchies, especially in when expressions, ensuring all cases are covered.

25. sealed interface

  • What: Similar to sealed class, but for interfaces. Limits the implementations to a predefined set i.e. all possible implementations are known at compile-time.
  • Why: It’s useful when you have a fixed set of implementations and want to ensure that no other types can implement the interface outside this scope.

26. in and out Variance ↔️

  • What: Keywords that define covariance (out) and contravariance (in) in generics.
  • Why: Helps in creating flexible and type-safe APIs by controlling how generic types are used.
  • Note: Use out when the generic type is only returned (produced), and in when it is only consumed (taken as input).

⭐️ Not completely aware about this part? or want to learn more on this?
Feel free to toggle to the linked blog for an in-depth understanding about variances: https://android-dev-nexus.medium.com/kotlin-generics-part-2-variance-and-star-projections-213209276050 😉 ⭐️

27. Kotlin Coroutines

  • What: Simplifies asynchronous programming by allowing code to be written sequentially.
  • Why: Makes managing background tasks, such as network requests or database operations, easier and more readable.

⭐️ Tip: Do checkout our Coroutines series and stay tuned for upcoming parts: https://android-dev-nexus.medium.com/list/coroutine-series-5495d60bb19b ⭐️

Conclusion:

  • val and var: Constant vs mutable variables.
  • lateinit and lazy: Delayed initialization.
  • Immutable collections: listOf, mapOf, emptyListOf(), emptyMapOf().
  • Mutable collections: mutableListOf, mutableMapOf.
  • forEach, forEachIndexed: Iterates over collections.
  • filter, any, takeIf: Filters or checks collections.
  • firstOrNull: Finds the first match or returns null.
  • when: Replaces complex if-else logic.
  • Higher-order functions: map, flatMap, transform.
  • Extension Functions: Adds functionality to existing classes.
  • Scope Functions: Enhances code readability with context-specific operations.
  • Companion Object: Equivalent to static methods in Kotlin
  • open: Enables inheritance in Kotlin.
  • data class: Simplifies data storage classes.
  • sealed class & sealed interface: Restricts class hierarchies.
  • Variance (in, out): Controls generic type usage.
  • Coroutines: Simplifies asynchronous programming.

Woo-hoo! You made it this far! Congratulations 🥳

For more tips, dive into our blog on Kotlin Best Practices to write efficient, high-quality code!

If you found this helpful, don’t forget to clap for the blog or buy us a coffee here ☕️! Follow for more such posts.
Until then, happy coding!

٩(^ᗜ^ )و

Android Dev Nexus
Android Dev Nexus

Written by Android Dev Nexus

Your friendly neighborhood developers working at PayPal, turning Android fundamentals into concepts you’ll actually understand.

Responses (4)

Write a response

This one is really good with all the important concepts. Can you please share a one for advanced concepts like coroutines?

Much needed cheatsheet. Thank you 😊

Ah, I gotta use this for my next interview