Sobes.tech
Junior

What auxiliary functions do you know or have used in your experience?

sobes.tech AI

Answer from AI

  • Lambda expressions: Shorten code for small handler functions, such as clicks or callbacks.

  • Extension Functions (Kotlin): Add new functions to existing classes without inheritance, improving readability and convenience.

    fun String.isPalindrome(): Boolean {
        // Checks if the string is a palindrome
        return this == this.reversed()
    }
    
  • Inline Functions (Kotlin): Embed the function body at the call site, reducing overhead of creating function objects, especially useful with lambdas.

    inline fun measureExecutionTime(block: () -> Unit) {
        // Measures the execution time of a code block
        val startTime = System.currentTimeMillis()
        block()
        val endTime = System.currentTimeMillis()
        println("Execution time: ${endTime - startTime} ms")
    }
    
  • Data Classes (Kotlin): Automatically generate equals(), hashCode(), toString(), copy(), which is convenient for data storage.

    data class User(val name: String, val age: Int)
    
  • Sealed Classes (Kotlin): Represent a limited hierarchy of classes, useful for modeling states or events, especially in combination with the when operator.

  • Generics: Allow creating reusable components that work with different data types.

    public class Box<T> {
        // Generic class for storing any data type
        private T data;
    
        public void setData(T data) {
            this.data = data;
        }
    
        public T getData() {
            return data;
        }
    }
    
  • Operations with collections (map, filter, reduce, etc.): Functional methods for processing data collections.

    val numbers = listOf(1, 2, 3, 4, 5)
    val squaredEvenNumbers = numbers
        .filter { it % 2 == 0 } // Filter even numbers
        .map { it * it }      // Square the numbers
    
  • Resource getters (Kotlin): For obtaining strings, colors, sizes, etc., from resources.

    val appName = context.getString(R.string.app_name)
    val primaryColor = ContextCompat.getColor(context, R.color.colorPrimary)
    
  • Nullable types and safe calls (Kotlin): Reduce NullPointerException occurrences.

    val name: String? = null
    val length = name?.length ?: 0 // Safe call and Elvis operator