Utility Function in Kotlin - runCatching, repeat, use, lazy.
1. runCatching
runCatching in Kotlin is a functional, concise alternative to traditional try-catch blocks. It executes a block of code, catches any Throwable exception, and wraps the outcome into a Result object, allowing for cleaner error handling.
Key Features
Encapsulates Results: It returns a Result, which is a Success(value) or Failure(exception).
Functional Chaining: You can chain operations like onSuccess, onFailure, map, and recover on the resulting object.
Non-Blocking: It does not throw exceptions; it treats them as data
2. use Function:
Specifically for Auto Closeable resources (like files); it ensures the resource is closed after the block executes.
Key Benefits
Conciseness: Reduces boilerplate code (try-finally blocks).
Reliability: Prevents memory leaks caused by forgetting to close resources.
3. repeat
Zero-Indexed: The function provides an integer parameter representing the current iteration index, starting at 0 and ending at times -1.
Under the Hood: It is an inline function that uses a simple standard for loop, meaning it adds zero performance overhead.
Key Benefits
Readability: Expresses intent clearly when the exact count of repetitions is all that matters.
Conciseness: Eliminates the boilerplate of writing for (i in 0 until 4).
4. lazy
lazy in Kotlin is a delegate used for lazy initialization, meaning a property is not created until it is accessed for the very first time.
It is highly useful for optimizing performance when dealing with expensive setups, like database creations or heavy API calls
How lazy Works?
Deferred Creation: The code inside the lazy block runs only once, during the first call.
Cached Value: Subsequent reads return the cached result without re-executing the block.
Read-Only: It can only be used with read-only properties.
Key Benefits
Performance: Saves memory and CPU cycles by ignoring unused properties.
Thread Safety: By default, lazy is synchronized so multiple threads can access it safely.
Telegram Group: https://t.me/androidNinjaWarrior
Github: https://github.com/krishna-matrix/Kot...
Guide to watch:
00:50 runCatching utility function in Kotlin
07:09 use utility function in Kotlin
10:30 repeat utility function in Kotlin
12:43 lazy utility function in Kotlin
17:23 How to commit and push file in IntelliJ Idea?
#utilityFunction #utility #runCatching #repeat #use #lazy #Kotlin #KotlinCompleteCourse #KotlinHindi
Disclaimer- Some content are used for educational purposes under fair use.
Copyright Disclaimer Under Section 107 of the Copyright Act 1976, allowance is made for "fair use" for purposes such as criticism, comment, news reporting, teaching, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use. All credit for copyright material used in the video goes to the respected Owner.
Thank you guys.