[{"categories":["Blog"],"date":"November 15, 2024","permalink":"https://agrawalsuneet.github.io/blogs/lambda-in-unreal/","section":"blogs","summary":"Lambda functions, or lambdas, are an essential tool in modern C++ programming and have powerful applications in Unreal Engine. They offer a concise way to define small, inline functions and are ideal for simplifying code, especially when working with delegates, multi-threaded tasks, or passing functions as parameters.\nIn this blog, we’ll explore what lambdas are, how they work in Unreal Engine, and practical examples for common use cases.\nWhat is a Lambda? A lambda is an anonymous function defined directly within code, often as an inline expression. Lambdas are beneficial when the function logic is simple and doesn\u0026rsquo;t need to be reused, as they reduce code clutter by avoiding the need for separate function declarations and definitions.\nIn Unreal Engine, lambdas are particularly useful for:\nEvent handling with delegates Multithreading with Async tasks Writing concise, inline code for loops or algorithms A lambda function in C++ has the following basic syntax:\n[/* capture */](/* parameters */) -\u0026gt; /* return type */ { /* function body */ }; Capture: Specifies which variables from the enclosing scope are available within the lambda. Parameters: The parameters that the lambda accepts. Return Type: Optional; usually inferred automatically. Function Body: The code that runs when the lambda is executed. 1. Using Lambdas with Single-cast Delegates Single-cast delegates in Unreal Engine allow you to bind a function to an event that can only have one listener. Lambdas are a perfect fit for these since you can easily define small, specific responses directly inline without creating additional functions.\nExample: Binding a Lambda to a Delegate // Declare a delegate DECLARE_DELEGATE(FOnJumpPressed); class AMyCharacter : public ACharacter { public: // Delegate instance FOnJumpPressed OnJumpPressedDelegate; void Jump() { OnJumpPressedDelegate.ExecuteIfBound(); } }; AMyCharacter* Character = GetMyCharacter(); // Bind a lambda to the delegate Character-\u0026gt;OnJumpPressedDelegate.BindLambda([]() { UE_LOG(LogTemp, Warning, TEXT(\u0026#34;Player pressed jump!\u0026#34;)); }); Character-\u0026gt;Jump(); // This will log \u0026#34;Player pressed jump!\u0026#34; In this example, we define a Jump function that triggers the OnJumpPressedDelegate. By binding a lambda to the delegate, we log a message whenever the jump function is called.\n2. Lambdas with Parameters Lambdas can accept parameters just like regular functions. This is especially useful for delegates that pass data to their listeners, such as when passing player input values or state changes.\nExample: Binding a Lambda with Parameters // Declare a delegate with parameters DECLARE_DELEGATE_OneParam(FOnHealthChanged, float); class AMyCharacter : public ACharacter { public: // Delegate instance FOnHealthChanged OnHealthChangedDelegate; void TakeDamage(float DamageAmount) { Health -= DamageAmount; OnHealthChangedDelegate.ExecuteIfBound(Health); // Pass health as parameter } private: float Health = 100.0f; }; AMyCharacter* Character = GetMyCharacter(); // Bind a lambda that accepts the current health as a parameter Character-\u0026gt;OnHealthChangedDelegate.BindLambda([](float CurrentHealth) { UE_LOG(LogTemp, Warning, TEXT(\u0026#34;Health changed! New Health: %f\u0026#34;), CurrentHealth); }); Character-\u0026gt;TakeDamage(20.0f); // This will log the new health value Here, OnHealthChangedDelegate is triggered whenever the character’s health changes. We bind a lambda that takes the current health as a parameter and logs it, making it easy to track health changes in real-time.\n3. Using Lambdas for Multithreading with Async The Async function in Unreal Engine simplifies running tasks on a separate thread, which is useful for tasks that could block the game thread, like heavy computations or network requests. Lambdas make it easy to define these tasks inline.\nExample: Running a Heavy Computation with Async and a Lambda // Perform a heavy computation asynchronously Async(EAsyncExecution::Thread, []() { int32 Result = 0; for (int32 i = 0; i \u0026lt; 1000000; ++i) { Result += i; // Simulate heavy computation } UE_LOG(LogTemp, Warning, TEXT(\u0026#34;Computation finished with result: %d\u0026#34;), Result); }); In this example, we execute a lambda on a separate thread to handle a heavy computation, which prevents it from blocking the game thread. Using Async with a lambda keeps the code compact and readable.\n4. Using Lambdas in Timers Unreal Engine’s GetWorldTimerManager().SetTimer function allows you to set up delayed events or recurring timers. Lambdas are convenient here, as they allow you to define the callback function directly within the timer call, making the code concise and keeping related logic in one place.\nExample: Setting Up a Timer with a Lambda FTimerHandle TimerHandle; GetWorldTimerManager().SetTimer(TimerHandle, []() { UE_LOG(LogTemp, Warning, TEXT(\u0026#34;Timer tick!\u0026#34;)); }, 1.0f, true); // Executes every second This code sets up a timer to log Timer tick! every second. Using a lambda for the callback keeps the timer setup code clean and concise.\n5. Capturing Variables in Lambdas Capturing variables in a lambda means allowing it to access variables from the surrounding scope. In Unreal, this can be handy when you need to use class members or external variables within the lambda body.\nThere are three common capture modes:\n[=]: Captures variables by value (a copy). [\u0026amp;]: Captures variables by reference (allows modification). [this]: Captures the current object by reference (used often in Unreal for class member access). Example: Capturing Variables in a Lambda float PlayerHealth = 100.0f; float Damage = 25.0f; // Lambda that captures PlayerHealth by reference and Damage by value auto ApplyDamage = [\u0026amp;, Damage]() { PlayerHealth -= Damage; UE_LOG(LogTemp, Warning, TEXT(\u0026#34;Player Health after damage: %f\u0026#34;), PlayerHealth); }; // Call the lambda ApplyDamage(); // Outputs updated health In this example, PlayerHealth is captured by reference (using [\u0026amp;]), allowing the lambda to modify it, while Damage is captured by value, creating a local copy of the original variable.\n6. Using Lambdas with TArray::Sort Lambdas are often used with Unreal\u0026rsquo;s array functions like Sort, FilterByPredicate, etc., to quickly define sorting or filtering behavior inline.\nExample: Sorting an Array of Integers with a Lambda TArray\u0026lt;int32\u0026gt; Scores = { 78, 95, 60, 89, 72 }; // Sort scores in descending order Scores.Sort([](int32 A, int32 B) { return A \u0026gt; B; // Sort descending }); for (int32 Score : Scores) { UE_LOG(LogTemp, Warning, TEXT(\u0026#34;Score: %d\u0026#34;), Score); } This lambda sorts an array of scores in descending order. By defining the sorting criteria directly in the lambda, you keep the code concise and focused.\nSummary Table of Lambda Use Cases in Unreal Engine Use Case Example Code Snippet Description Single-cast Delegate Binding Delegate.BindLambda([](){ /*...*/ }); Inline event handling for specific events Delegate with Parameters Delegate.BindLambda([](float Value){ /*...*/ }); Passes parameters to inline delegate actions Async Task Execution Async(EAsyncExecution::Thread, [](){ /*...*/ }); Runs heavy tasks on separate threads Timer Callback SetTimer(TimerHandle, [](){ /*...*/ }, 1.0f, true); Inline timer callbacks Capture by Reference/Value auto Lambda = [\u0026amp;, Var](){ /*...*/ }; Access outer scope variables in lambda Array Sorting Array.Sort([](Type A, Type B) { return A \u0026lt; B; }); Custom sort directly within Sort function Conclusion Lambdas are versatile, anonymous functions that add flexibility and conciseness to Unreal Engine code. By using them with delegates, timers, async tasks, and sorting functions, you can streamline code and keep related functionality localized to the place where it’s needed. Whether you’re handling input events, managing game state, or creating efficient multithreaded tasks, lambdas can help you keep your Unreal Engine codebase efficient and readable.\n","tags":["Unreal"],"title":"Lambda in Unreal"},{"categories":["Blog"],"date":"November 1, 2024","permalink":"https://agrawalsuneet.github.io/blogs/delegates-in-unreal/","section":"blogs","summary":"Delegates in Unreal Engine play an essential role in creating modular, decoupled, and event-driven code. They allow one object to call a function on another object without hard-wiring the dependency between them, which is perfect for implementing event-driven behavior. In Unreal, delegates are especially useful in game development to handle events, respond to actions, or manage callbacks.\nIn this blog, we\u0026rsquo;ll go through the different types of delegates in Unreal Engine, explaining what they are, how they differ, and providing code examples for each type.\nWhat is a Delegate? A delegate in Unreal is a type-safe callback mechanism that allows one part of code to \u0026ldquo;delegate\u0026rdquo; functionality to another. Delegates are powerful tools to manage responses to actions, such as when a player triggers a specific action or when a game object completes an animation or reaches a target location.\nIn Unreal Engine, there are four main types of delegates:\nSingle-cast Delegates Multi-cast Delegates Dynamic Single-cast Delegates Dynamic Multi-cast Delegates Let’s take a deeper look into each type.\n1. Single-cast Delegates A single-cast delegate is a delegate that can have only one binding at any given time. This is useful for situations where only one object needs to respond to a particular event.\nHow to Declare and Use Single-cast Delegates // Declare a Single-cast Delegate DECLARE_DELEGATE(FOnHealthChanged); // A class using Single-cast Delegate class APlayerCharacter : public ACharacter { public: // The single-cast delegate instance FOnHealthChanged OnHealthChangedDelegate; void TakeDamage(float DamageAmount) { Health -= DamageAmount; OnHealthChangedDelegate.ExecuteIfBound(); // Trigger the delegate } }; Binding and Executing a Single-cast Delegate APlayerCharacter* Player = GetPlayerCharacter(); Player-\u0026gt;OnHealthChangedDelegate.BindLambda([]() { UE_LOG(LogTemp, Warning, TEXT(\u0026#34;Player\u0026#39;s health has changed!\u0026#34;)); }); Player-\u0026gt;TakeDamage(50.0f); // This will call the delegate if health changes 2. Multi-cast Delegates A multi-cast delegate can bind multiple functions to a single event, allowing multiple listeners to respond when the event occurs. Multi-cast delegates are perfect when multiple systems or actors need to respond to the same event, such as a global game event that should notify various UI elements.\nHow to Declare and Use Multi-cast Delegates // Declare a Multi-cast Delegate DECLARE_MULTICAST_DELEGATE(FOnPlayerDied); // A class using Multi-cast Delegate class AGameModeBase : public AGameMode { public: // The multi-cast delegate instance FOnPlayerDied OnPlayerDiedDelegate; void PlayerDeath() { OnPlayerDiedDelegate.Broadcast(); // Notify all listeners } }; Binding and Executing a Multi-cast Delegate AGameModeBase* GameMode = GetWorld()-\u0026gt;GetAuthGameMode\u0026lt;AGameModeBase\u0026gt;(); // Binding multiple listeners GameMode-\u0026gt;OnPlayerDiedDelegate.AddLambda([]() { UE_LOG(LogTemp, Warning, TEXT(\u0026#34;Listener 1: Player has died!\u0026#34;)); }); GameMode-\u0026gt;OnPlayerDiedDelegate.AddLambda([]() { UE_LOG(LogTemp, Warning, TEXT(\u0026#34;Listener 2: Player has died!\u0026#34;)); }); // Trigger the delegate GameMode-\u0026gt;PlayerDeath(); When PlayerDeath() is called, both listeners will log a message to the console.\n3. Dynamic Single-cast Delegates Dynamic single-cast delegates can be serialized and exposed to Blueprints. They are useful when you need to bind a function that can be called in both C++ and Blueprints. This is ideal when creating modular systems that may be extended by designers in the Unreal Editor.\nHow to Declare and Use Dynamic Single-cast Delegates // Declare a Dynamic Single-cast Delegate DECLARE_DYNAMIC_DELEGATE(FOnHealthRestored); class AHealingStation : public AActor { GENERATED_BODY() public: // The dynamic single-cast delegate instance FOnHealthRestored OnHealthRestoredDelegate; void HealPlayer() { OnHealthRestoredDelegate.ExecuteIfBound(); } }; Binding a Dynamic Single-cast Delegate AHealingStation* HealingStation = GetWorld()-\u0026gt;SpawnActor\u0026lt;AHealingStation\u0026gt;(); HealingStation-\u0026gt;OnHealthRestoredDelegate.BindDynamic(this, \u0026amp;AMyClass::OnPlayerHealed); void AMyClass::OnPlayerHealed() { UE_LOG(LogTemp, Warning, TEXT(\u0026#34;Player healed through a dynamic delegate!\u0026#34;)); } HealingStation-\u0026gt;HealPlayer(); // This will trigger OnPlayerHealed 4. Dynamic Multi-cast Delegates Dynamic multi-cast delegates can bind multiple functions and are also exposed to Blueprints. They are useful for managing events where both C++ and Blueprint classes might need to respond, making them ideal for gameplay events such as starting or ending a game round.\nHow to Declare and Use Dynamic Multi-cast Delegates // Declare a Dynamic Multi-cast Delegate DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnRoundStarted); class AGameModeBase : public AGameMode { GENERATED_BODY() public: // The dynamic multi-cast delegate instance UPROPERTY(BlueprintAssignable) FOnRoundStarted OnRoundStartedDelegate; void StartRound() { OnRoundStartedDelegate.Broadcast(); // Notify all bound listeners } }; Binding a Dynamic Multi-cast Delegate in Blueprints Dynamic multi-cast delegates can be bound directly in Blueprints by dragging the OnRoundStarted event into the Blueprint editor. This makes it easy to integrate C++ and Blueprint functionality for events that multiple Blueprint scripts need to react to.\nUsing Parameters and Return Types with Delegates Delegates can be defined to accept parameters and, in some cases, a return type, which allows data to be passed directly through the delegate. Here is a breakdown of what is supported by each type:\nSingle-cast delegates: Support parameters and return types. Multi-cast delegates: Support parameters but not return types, as multiple listeners could return conflicting values. Dynamic single-cast delegates: Support parameters but not return types. Dynamic multi-cast delegates: Support parameters but not return types. To define delegates with parameters, you can use Unreal\u0026rsquo;s parameterized macros, such as DECLARE_DELEGATE_OneParam or DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam. To add a return type, use macros like DECLARE_DELEGATE_RetVal.\nFor example, here’s a single-cast delegate with a float parameter and a bool return type:\n// Declare a Single-cast Delegate with Parameter and Return Type DECLARE_DELEGATE_RetVal_OneParam(bool, FOnHealthCheck, float); class APlayerCharacter : public ACharacter { public: // The single-cast delegate instance with a float parameter and a bool return type FOnHealthCheck OnHealthCheckDelegate; bool CheckHealth(float Threshold) { if (OnHealthCheckDelegate.IsBound()) { return OnHealthCheckDelegate.Execute(Threshold); } return false; } }; You could then bind a function or lambda to this delegate that returns true or false based on the health threshold.\nComparison Table Delegate Type Supports Parameters Supports Return Type Blueprint Accessible Single-cast Delegate Yes Yes No Multi-cast Delegate Yes No No Dynamic Single-cast Delegate Yes No Yes Dynamic Multi-cast Delegate Yes No Yes Conclusion Delegates are essential for creating event-driven systems in Unreal Engine, providing flexibility, modularity, and ease of use. Understanding when to use each type of delegate (single-cast vs. multi-cast, dynamic vs. non-dynamic) helps in designing scalable and responsive game systems. Using the right delegate type ensures that your code is maintainable, whether working in C++ or Blueprint, and opens up creative ways to trigger events across your game’s actors and components.\n","tags":["Unreal"],"title":"Delegates in Unreal"},{"categories":["Blog"],"date":"October 13, 2023","permalink":"https://agrawalsuneet.github.io/blogs/get-and-set-methods-with-date-objects-in-javascript/","section":"blogs","summary":"Working with dates is a common task in web development, and JavaScript provides a built-in Date object to handle date and time-related operations. Two essential methods for manipulating Date objects are get and set methods. In this blog, we will explore how to use these methods to retrieve and modify various components of a Date object.\nThe Date Object Before we delve into the get and set methods, let\u0026rsquo;s briefly revisit the Date object itself. You can create a new Date object in JavaScript as follows:\nconst currentDate = new Date(); This creates a Date object representing the current date and time. Now, let\u0026rsquo;s explore the get and set methods for working with Date objects.\nGet Methods Getting the Year To retrieve the year from a Date object, you can use the getFullYear() method:\nconst currentYear = currentDate.getFullYear(); console.log(\u0026#34;Current year: \u0026#34; + currentYear); Getting the Month To get the month (0-11) from a Date object, you can use the getMonth() method:\nconst currentMonth = currentDate.getMonth(); console.log(\u0026#34;Current month: \u0026#34; + currentMonth); Getting the Day of the Month To retrieve the day of the month (1-31), you can use the getDate() method:\nconst currentDay = currentDate.getDate(); console.log(\u0026#34;Current day: \u0026#34; + currentDay); Getting the Day of the Week To get the day of the week (0-6, where 0 is Sunday and 6 is Saturday), you can use the getDay() method:\nconst currentDayOfWeek = currentDate.getDay(); console.log(\u0026#34;Current day of the week: \u0026#34; + currentDayOfWeek); Getting the Hours, Minutes, and Seconds You can use the getHours(), getMinutes(), and getSeconds() methods to retrieve the current time components:\nconst currentHour = currentDate.getHours(); const currentMinute = currentDate.getMinutes(); const currentSecond = currentDate.getSeconds(); console.log(\u0026#34;Current time: \u0026#34; + currentHour + \u0026#34;:\u0026#34; + currentMinute + \u0026#34;:\u0026#34; + currentSecond); Set Methods Setting the Year To set the year of a Date object, you can use the setFullYear(year) method:\ncurrentDate.setFullYear(2024); console.log(\u0026#34;New date with updated year: \u0026#34; + currentDate); Setting the Month To set the month, use the setMonth(month) method, where month is a value between 0 (January) and 11 (December):\ncurrentDate.setMonth(2); // March console.log(\u0026#34;New date with updated month: \u0026#34; + currentDate); Setting the Day of the Month To change the day of the month, use the setDate(day) method:\ncurrentDate.setDate(15); console.log(\u0026#34;New date with updated day of the month: \u0026#34; + currentDate); Setting the Hours, Minutes, and Seconds You can set the time components using the setHours(hours), setMinutes(minutes), and setSeconds(seconds) methods:\ncurrentDate.setHours(14, 30, 0); // Set the time to 14:30:00 console.log(\u0026#34;New date with updated time: \u0026#34; + currentDate); Conclusion In this blog, we\u0026rsquo;ve explored how to work with Date objects in JavaScript using the get and set methods. These methods are invaluable for extracting and modifying various components of Date objects, making them a crucial tool for any developer working with date and time-related data in their JavaScript applications. Whether you\u0026rsquo;re building a calendar application, a scheduling tool, or any other time-dependent system, mastering these methods is essential for accurate date manipulation.\n","tags":["JavaScript"],"title":"Get and Set Methods with Date Objects in JavaScript"},{"categories":["Blog"],"date":"October 11, 2023","permalink":"https://agrawalsuneet.github.io/blogs/date-comparison-in-javascript/","section":"blogs","summary":"Working with dates is a common task in web development, and JavaScript provides a powerful set of tools for manipulating and comparing dates. Whether you\u0026rsquo;re building a scheduling application, calculating the age of a user, or implementing date-based logic, understanding how to compare dates in JavaScript is essential. In this guide, we\u0026rsquo;ll explore various techniques and best practices for comparing dates in JavaScript.\nDate Objects in JavaScript JavaScript provides the Date object to work with dates and times. You can create a new Date object using one of the following methods:\n// Creating a new Date object with the current date and time const currentDate = new Date(); // Creating a Date object from a specific date and time const specificDate = new Date(\u0026#39;2023-10-11T12:00:00\u0026#39;); // Creating a Date object by specifying year, month, day, hour, minute, second const customDate = new Date(2023, 9, 11, 12, 0, 0); // Note: Month is zero-based (0 = January, 11 = December) Comparing Dates in JavaScript When comparing dates in JavaScript, there are various scenarios to consider, such as equality, order (before or after), and time zone differences. Here are different approaches for comparing dates:\nEquality Check To check if two dates are equal, you can use the equality operator (===) or the getTime() method to compare the numeric values of the dates:\nconst date1 = new Date(\u0026#39;2023-10-11\u0026#39;); const date2 = new Date(\u0026#39;2023-10-11\u0026#39;); // Using the equality operator const areDatesEqual = date1.getTime() === date2.getTime(); // Using the getTime() method const areDatesEqual = date1.getTime() === date2.getTime(); Comparing Order (Before or After) You may need to compare dates to determine which date comes before or after another. You can use the comparison operators (\u0026lt;, \u0026lt;=, \u0026gt;, \u0026gt;=) or the getTime() method to compare the numeric values:\nconst date1 = new Date(\u0026#39;2023-10-11\u0026#39;); const date2 = new Date(\u0026#39;2023-10-12\u0026#39;); // Using comparison operators const isDate1BeforeDate2 = date1 \u0026lt; date2; // true // Using getTime() method const isDate1BeforeDate2 = date1.getTime() \u0026lt; date2.getTime(); // true Finding the Difference Between Dates To find the difference between two dates in various units (e.g., days, hours, minutes), you can subtract the dates and convert the result to the desired unit. Here\u0026rsquo;s an example of finding the difference in days:\nconst date1 = new Date(\u0026#39;2023-10-11\u0026#39;); const date2 = new Date(\u0026#39;2023-10-15\u0026#39;); const timeDifferenceInMilliseconds = date2 - date1; const daysDifference = timeDifferenceInMilliseconds / (1000 * 60 * 60 * 24); // 4 days You can apply the same concept to find the difference in hours, minutes, or seconds by changing the divisor accordingly.\nComparing Date, Day, Month, or Year Parts Separately If you need to compare only specific parts of two date objects, you can extract those parts and compare them. Here\u0026rsquo;s how you can compare the year, month, day, and day of the week separately:\nconst date1 = new Date(\u0026#39;2023-10-11\u0026#39;); const date2 = new Date(\u0026#39;2023-10-15\u0026#39;); const areYearsEqual = date1.getFullYear() === date2.getFullYear(); // true const areMonthsEqual = date1.getMonth() === date2.getMonth(); // true const areDaysEqual = date1.getDate() === date2.getDate(); // false const areDaysOfWeekEqual = date1.getDay() === date2.getDay(); // 2 (Tuesday) !== 6 (Saturday) By using these methods, you can focus on the specific parts of the dates you\u0026rsquo;re interested in comparing.\nUsing Third-Party Libraries While JavaScript provides the basic functionality for date comparison, you may find it helpful to use third-party libraries for more advanced date manipulation and comparison. Some popular date libraries include:\nMoment.js (Deprecated): Although Moment.js is no longer actively maintained, it remains widely used for date and time manipulation. It offers comprehensive features for parsing, formatting, and comparing dates. date-fns: A modern JavaScript date utility library that provides a consistent and reliable way to work with dates. It has a wide range of functions for date manipulation and comparison. Luxon: A library for handling dates and times with a focus on simplicity and correctness. It provides a simple and intuitive API for parsing, formatting, and comparing dates. Day.js: A minimalist JavaScript library for working with dates and times. It is designed to be lightweight and fast, making it an excellent choice for simple date manipulations. Conclusion Comparing dates in JavaScript is a fundamental skill for web developers. Whether you\u0026rsquo;re building a calendar application or working with time-based data, understanding how to compare and manipulate dates is crucial. By using JavaScript\u0026rsquo;s built-in features and third-party libraries, you can perform date comparisons accurately and efficiently. Remember to account for time zone differences when necessary and choose the approach that best suits your specific use case. Additionally, you can extract and compare specific date parts to fine-tune your date comparisons.\n","tags":["JavaScript"],"title":"Date Comparison in JavaScript"},{"categories":["Blog"],"date":"October 9, 2023","permalink":"https://agrawalsuneet.github.io/blogs/map-vs-weak-map-in-javascript/","section":"blogs","summary":"JavaScript provides various data structures to manage collections of key-value pairs, and two commonly used ones are Map and WeakMap. Both are used to associate values with keys, but they have distinct characteristics and use cases. In this blog, we will explore the differences between Map and WeakMap with examples to help you understand when to use each one.\nMap A Map is a built-in JavaScript data structure introduced in ECMAScript 6 (ES6) that allows you to store key-value pairs where the keys can be of any type, including objects and primitive types. Map is especially useful when you need to maintain a mapping of keys to values, and it preserves the order of key insertion. Here\u0026rsquo;s an example of how to create and use a Map:\n// Creating a Map const myMap = new Map(); // Adding key-value pairs to the Map const key1 = \u0026#39;name\u0026#39;; const value1 = \u0026#39;Alice\u0026#39;; myMap.set(key1, value1); const key2 = { id: 1 }; const value2 = \u0026#39;Bob\u0026#39;; myMap.set(key2, value2); // Getting values from the Map console.log(myMap.get(key1)); // Output: \u0026#39;Alice\u0026#39; console.log(myMap.get(key2)); // Output: \u0026#39;Bob\u0026#39; // Checking if a key exists in the Map console.log(myMap.has(key1)); // Output: true // Deleting a key-value pair from the Map myMap.delete(key1); // Iterating through the Map for (const [key, value] of myMap) { console.log(key, value); } WeakMap A WeakMap is similar to a Map in that it stores key-value pairs, but it has a crucial difference: it can only use objects as keys and does not prevent those objects from being garbage collected when they are no longer in use. This behavior makes WeakMap suitable for scenarios where you want to associate metadata with objects or manage relationships without preventing them from being automatically cleaned up by the garbage collector. Here\u0026rsquo;s an example:\n// Creating a WeakMap const myWeakMap = new WeakMap(); // Creating objects to use as keys const key1 = { id: 1 }; const key2 = { id: 2 }; // Adding key-value pairs to the WeakMap myWeakMap.set(key1, \u0026#39;Alice\u0026#39;); myWeakMap.set(key2, \u0026#39;Bob\u0026#39;); // Getting values from the WeakMap console.log(myWeakMap.get(key1)); // Output: \u0026#39;Alice\u0026#39; console.log(myWeakMap.get(key2)); // Output: \u0026#39;Bob\u0026#39; // Checking if a key exists in the WeakMap console.log(myWeakMap.has(key1)); // Output: true // Deleting a key-value pair from the WeakMap myWeakMap.delete(key1); // The WeakMap automatically removes references to deleted keys console.log(myWeakMap.has(key1)); // Output: false Differences Between Map and WeakMap Now that we\u0026rsquo;ve discussed Map and WeakMap individually, let\u0026rsquo;s highlight the key differences between them:\nKey Types: Map: Map can use any type of value as a key, including primitive types (numbers, strings, booleans), objects, and even functions. WeakMap: WeakMap can only use objects as keys. Attempting to use non-object values as keys will result in an error. This restriction is because WeakMap is designed to work with object references. Garbage Collection: Map: Objects used as keys in a Map are held by strong references, meaning they won\u0026rsquo;t be garbage collected as long as the Map retains a reference to them. This can lead to memory leaks if you unintentionally retain objects. WeakMap: Objects used as keys in a WeakMap are held by weak references, allowing them to be garbage collected as soon as no other strong references to those objects exist. This behavior is useful for scenarios where you want to avoid memory leaks and allow automatic cleanup of objects. Iteration: Map: Map allows easy iteration through key-value pairs in a predictable order, maintaining the insertion order of keys. WeakMap: WeakMap does not provide direct iteration methods, and you typically use it for value retrieval rather than iteration. It does not guarantee any specific order of key-value pairs. Size Property: Map: Map has a size property that allows you to determine the number of key-value pairs it contains. WeakMap: WeakMap does not have a size property, so you cannot directly obtain the number of key-value pairs it contains. Use Cases Now, let\u0026rsquo;s explore the common use cases for both Map and WeakMap to help you understand when to use each one:\nUse Map When: Maintaining Key-Value Pairs: You need to maintain a collection of key-value pairs, and the keys can be of diverse types, including both primitive values and objects. Iteration and Predictable Order: You require easy iteration through the key-value pairs and want to ensure that the order of insertion is preserved. Strong References: You want to ensure that the objects used as keys are not garbage collected as long as they are associated with the Map. Diverse Key Types: You need to use various types of values as keys, including non-object types like strings and numbers. Use WeakMap When: Associating Metadata with Objects: You want to associate additional information or metadata with objects but don\u0026rsquo;t want to prevent those objects from being garbage collected when they are no longer in use. Object Relationships: You need to create relationships between objects, and you want these relationships to be automatically cleaned up when the objects are no longer referenced by other parts of your code. Avoiding Memory Leaks: You\u0026rsquo;re concerned about potential memory leaks when working with long-lived objects and want to ensure that the garbage collector can reclaim memory efficiently. Exclusively for Objects: You need to use objects as keys, and you\u0026rsquo;re not interested in associating non-object values with keys. Conclusion In this blog, we\u0026rsquo;ve explored the differences between Map and WeakMap in JavaScript, two essential data structures for managing key-value pairs. Understanding the distinctions between these structures is crucial for making informed decisions when working with collections of data in your JavaScript applications.\nMap is versatile and suitable for scenarios where you need to maintain key-value pairs, regardless of the types of keys, while preserving insertion order. It\u0026rsquo;s perfect for situations where you want to maintain strong references to keys.\nWeakMap, on the other hand, is specialized for use with objects as keys. It allows you to associate metadata with objects and create object relationships without preventing those objects from being garbage collected. This is particularly valuable for avoiding memory leaks and ensuring efficient memory management.\nWhen choosing between Map and WeakMap, consider the specific use case and requirements of your application. By doing so, you can harness the power of these data structures to build more efficient and robust JavaScript applications. Understanding their key differences and appropriate use cases will enable you to make informed decisions and write cleaner, more efficient code.\n","tags":["JavaScript"],"title":"Map vs WeakMap in JavaScript"},{"categories":["Blog"],"date":"October 7, 2023","permalink":"https://agrawalsuneet.github.io/blogs/set-vs-weak-set-in-javascript/","section":"blogs","summary":"JavaScript provides various data structures to manage collections of data, and two commonly used ones are Set and WeakSet. Both are used to store collections of values, but they have distinct characteristics and use cases. In this blog, we will explore the differences between Set and WeakSet with examples to help you understand when to use each one.\nSet A Set is a built-in JavaScript data structure introduced in ECMAScript 6 (ES6) that allows you to store a collection of unique values. It can store any type of values, including primitive types and objects. Here\u0026rsquo;s an example of how to create and use a Set:\n// Creating a Set const mySet = new Set(); // Adding values to the Set mySet.add(1); mySet.add(\u0026#39;Hello\u0026#39;); mySet.add({ name: \u0026#39;John\u0026#39; }); // Checking the size of the Set console.log(mySet.size); // Output: 3 // Checking if a value exists in the Set console.log(mySet.has(\u0026#39;Hello\u0026#39;)); // Output: true // Deleting a value from the Set mySet.delete(\u0026#39;Hello\u0026#39;); // Iterating through the Set for (const item of mySet) { console.log(item); } WeakSet A WeakSet is also a collection of values, but it has a different purpose and behavior compared to Set. The primary difference is that a WeakSet can only store objects and does not prevent those objects from being garbage collected when they are no longer in use. This means that a WeakSet does not hold strong references to its elements, making it suitable for scenarios where you want to store objects but don\u0026rsquo;t want to prevent them from being automatically cleaned up by the garbage collector. Here\u0026rsquo;s an example:\n// Creating a WeakSet const myWeakSet = new WeakSet(); // Adding objects to the WeakSet const obj1 = { name: \u0026#39;Alice\u0026#39; }; const obj2 = { name: \u0026#39;Bob\u0026#39; }; myWeakSet.add(obj1); myWeakSet.add(obj2); // Checking if an object exists in the WeakSet console.log(myWeakSet.has(obj1)); // Output: true // Deleting an object from the WeakSet myWeakSet.delete(obj1); // The WeakSet automatically removes references to deleted objects console.log(myWeakSet.has(obj1)); // Output: false Differences Between Set and WeakSet Now that we\u0026rsquo;ve discussed Set and WeakSet individually, let\u0026rsquo;s highlight the key differences between them:\nAllowed Values: Set: Set can store any type of values, including primitive types (numbers, strings, booleans) and objects. It ensures that only unique values are stored. WeakSet: WeakSet can only store objects. Attempting to add non-object values like numbers or strings will result in an error. This restriction is because WeakSet is designed to work with object references. Garbage Collection: Set: Objects stored in a Set are held by strong references, meaning they won\u0026rsquo;t be garbage collected as long as the Set retains a reference to them. This can lead to memory leaks if you unintentionally retain objects. WeakSet: Objects stored in a WeakSet are held by weak references, allowing them to be garbage collected as soon as no other strong references to those objects exist. This behavior is useful for scenarios where you want to avoid memory leaks and allow automatic cleanup of objects. Iteration Order: Set: Set maintains the insertion order of values. When you iterate over a Set, values are returned in the order they were added. WeakSet: WeakSet does not provide a way to iterate over its elements. This is because it doesn\u0026rsquo;t guarantee any specific order, and it\u0026rsquo;s primarily used for managing object relationships rather than value retrieval. Size Property: Set: Set has a size property that allows you to determine the number of elements it contains. WeakSet: WeakSet does not have a size property, so you cannot directly obtain the number of elements it contains. You typically use WeakSet for membership checks and object management rather than counting its elements. Use Cases: Set: Use Set when you need to manage collections of unique values and order matters, or when you want to use non-primitive values as keys. WeakSet: Use WeakSet when you want to store objects but do not want to prevent them from being garbage collected, or when you need to create relationships between objects without strong references. Use Cases Now that we\u0026rsquo;ve seen the basic differences between Set and WeakSet, let\u0026rsquo;s discuss when to use each one.\nUse Set When: You need to store a collection of unique values, and the order of insertion matters. You want to use non-primitive values (objects, arrays) as keys. You want to maintain strong references to the values in the collection. Use WeakSet When: You want to store a collection of objects and don\u0026rsquo;t want to prevent them from being garbage collected. You need to associate metadata or additional information with objects. You want to create relationships between objects without preventing them from being released when they are no longer needed. Conclusion In summary, Set and WeakSet are both useful data structures in JavaScript, but they serve different purposes. Set is ideal for managing collections of unique values, while WeakSet is designed for managing objects and allows them to be garbage collected when they are no longer referenced. Choosing the right data structure depends on your specific use case and requirements. Understanding these differences will help you make informed decisions when working with collections in JavaScript.\n","tags":["JavaScript"],"title":"Set vs WeakSet in JavaScript"},{"categories":["Blog"],"date":"October 5, 2023","permalink":"https://agrawalsuneet.github.io/blogs/while-and-do-while-loop-in-c++/","section":"blogs","summary":"Loops are fundamental constructs in programming that allow us to repeat a block of code multiple times. In C++, two commonly used loop structures are the while loop and the do-while loop. In this blog post, we\u0026rsquo;ll dive into these loops, understand their syntax, and provide examples to illustrate their usage.\nThe While Loop The while loop is a conditional loop that repeats a block of code as long as a specified condition is true. Here\u0026rsquo;s the basic syntax:\nwhile (condition) { // Code to be executed while the condition is true } Counting from 1 to 10 #include \u0026lt;iostream\u0026gt; int main() { int i = 1; while (i \u0026lt;= 10) { std::cout \u0026lt;\u0026lt; i \u0026lt;\u0026lt; \u0026#34; \u0026#34;; i++; } return 0; } In this example, the while loop continues to execute as long as i is less than or equal to 10. It prints numbers from 1 to 10.\nThe Do-While Loop The do-while loop is similar to the while loop, but it guarantees that the loop body will be executed at least once before checking the condition for continuation. Here\u0026rsquo;s the basic syntax:\ndo { // Code to be executed } while (condition); User Input Validation #include \u0026lt;iostream\u0026gt; int main() { int userChoice; do { std::cout \u0026lt;\u0026lt; \u0026#34;Please enter a number between 1 and 5: \u0026#34;; std::cin \u0026gt;\u0026gt; userChoice; } while (userChoice \u0026lt; 1 || userChoice \u0026gt; 5); std::cout \u0026lt;\u0026lt; \u0026#34;You entered a valid number: \u0026#34; \u0026lt;\u0026lt; userChoice \u0026lt;\u0026lt; std::endl; return 0; } In this example, the program repeatedly prompts the user for input until they enter a number between 1 and 5.\nKey Differences between While and Do-While While both while and do-while loops are used for repetitive tasks, they differ in when they check the loop condition:\nIn a while loop, the condition is checked before entering the loop. If the condition is initially false, the loop will not execute at all. In a do-while loop, the condition is checked after executing the loop body once. This guarantees that the loop body will run at least once, even if the condition is false initially. Conclusion In C++, the while and do-while loops are essential tools for controlling program flow when you need to execute a block of code repeatedly based on a condition. Understanding the differences between these two loops and knowing when to use each is crucial for writing efficient and bug-free code. Practice with various examples to master their usage, and you\u0026rsquo;ll be well on your way to becoming a proficient C++ programmer.\n","tags":["C++"],"title":"While and Do-While Loop in C++"},{"categories":["Blog"],"date":"October 3, 2023","permalink":"https://agrawalsuneet.github.io/blogs/for-and-foreach-loop-in-c++/","section":"blogs","summary":"When it comes to repetitive tasks in programming, loops are a powerful and versatile tool that can simplify your code and make it more efficient. In C++, two commonly used loops are the for loop and the for each loop. In this comprehensive guide, we\u0026rsquo;ll explore both types of loops in C++ and provide you with various examples to help you master their usage.\nAnatomy of a for Loop Before we dive into examples, let\u0026rsquo;s review the basic structure of a for loop in C++:\nfor (initialization; condition; increment/decrement) { // Code to be executed } Here\u0026rsquo;s what each part does:\nInitialization: This part is executed only once at the beginning of the loop. It typically initializes a loop control variable (e.g., int i = 0). Condition: The loop continues as long as the condition is true. When the condition becomes false, the loop terminates. If the condition is false from the start, the loop may not execute at all. Increment/Decrement: This part is executed at the end of each iteration and is usually used to modify the loop control variable (e.g., i++ or i\u0026ndash;). Code to be executed: The block of code enclosed in curly braces {} is the body of the loop. It\u0026rsquo;s executed repeatedly until the condition becomes false. Printing Numbers with a for Loop #include \u0026lt;iostream\u0026gt; int main() { for (int i = 1; i \u0026lt;= 5; i++) { std::cout \u0026lt;\u0026lt; i \u0026lt;\u0026lt; \u0026#34; \u0026#34;; } return 0; } Output:\n1 2 3 4 5 In this example, we use a for loop to print numbers from 1 to 5. The loop control variable i is initialized to 1, and the loop continues as long as i is less than or equal to 5. After each iteration, i is incremented by 1.\nSum of Numbers with a for Loop #include \u0026lt;iostream\u0026gt; int main() { int sum = 0; for (int i = 1; i \u0026lt;= 5; i++) { sum += i; } std::cout \u0026lt;\u0026lt; \u0026#34;Sum of numbers: \u0026#34; \u0026lt;\u0026lt; sum \u0026lt;\u0026lt; std::endl; return 0; } Output:\nSum of numbers: 15 In this example, we calculate the sum of numbers from 1 to 5 using a for loop. The sum variable accumulates the values of i in each iteration.\nAnatomy of a for each Loop The for each loop, also known as the range-based for loop, is a more recent addition to C++ and simplifies the iteration over elements in a container, such as an array or a collection. Here\u0026rsquo;s the basic structure of a for each loop:\nfor (datatype element : container) { // Code to be executed for each element } In this loop:\ndatatype is the type of elements in the container. element is a variable that takes on the value of each element in the container in each iteration. container is the collection or sequence of elements you want to iterate over. Iterating Over an Array with a for each Loop #include \u0026lt;iostream\u0026gt; int main() { int numbers[] = {1, 2, 3, 4, 5}; for (int number : numbers) { std::cout \u0026lt;\u0026lt; number \u0026lt;\u0026lt; \u0026#34; \u0026#34;; } return 0; } Output:\n1 2 3 4 5 In this example, we use a for each loop to iterate through an array of integers and print each element. The loop automatically handles the iteration, and you don\u0026rsquo;t need to manage an index variable like in the previous for loop example.\nSum of Numbers with a for each Loop #include \u0026lt;iostream\u0026gt; #include \u0026lt;vector\u0026gt; int main() { std::vector\u0026lt;int\u0026gt; numbers = {1, 2, 3, 4, 5}; int sum = 0; for (int number : numbers) { sum += number; } std::cout \u0026lt;\u0026lt; \u0026#34;Sum of numbers: \u0026#34; \u0026lt;\u0026lt; sum \u0026lt;\u0026lt; std::endl; return 0; } Output:\nSum of numbers: 15 Here, we calculate the sum of numbers stored in a std::vector using a for each loop. The loop automatically iterates through the container, making it convenient for working with collections.\nConclusion In C++, both the for loop and the for each loop are essential tools for controlling the flow of your program when you need to repeat a block of code multiple times or iterate through collections. By mastering these loops and understanding their differences, you can make your code more efficient and concise. Experiment with the provided examples and practice using both types of loops in your own programs to become proficient in their usage.\n","tags":["C++"],"title":"For and Foreach Loop in C++"},{"categories":["Blog"],"date":"October 1, 2023","permalink":"https://agrawalsuneet.github.io/blogs/forward-declaration-in-c++/","section":"blogs","summary":"In C++, `forward declaration`` is a powerful tool that allows you to declare the existence of various entities before providing their full definitions. This technique is particularly useful for resolving circular dependencies, improving code organization, and optimizing compile times. In this blog post, we will explore forward declaration for a wide range of C++ entities, including classes, structs, enums, functions, variables, namespaces, class templates, and even friend functions.\nForward Declaration for Classes One of the most common use cases for forward declaration is dealing with classes, especially in situations where two classes depend on each other. Here\u0026rsquo;s an example of forward declaring two classes, ClassA and ClassB, to break a circular dependency:\n// Forward declaration for ClassB class ClassB; class ClassA { public: ClassB* bInstance; }; class ClassB { public: ClassA* aInstance; }; Forward Declaration for Structs Structs can also be forward declared in a similar way to classes. Here\u0026rsquo;s an example where two structs, StructX and StructY, reference each other:\n// Forward declaration for StructY struct StructY; struct StructX { StructY* yInstance; }; struct StructY { StructX* xInstance; }; Forward Declaration for Enums Enums can be forward declared when you need to use them before their actual definition. Here\u0026rsquo;s an example:\n// Forward declaration for Color enum class Color : int; void printColor(Color color); enum class Color : int { Red, Green, Blue }; Forward Declaration for Functions Forward declaration for functions is useful when you want to declare a function before defining or using it. For instance:\n// Forward declaration for function void forwardDeclaredFunction(); int main() { forwardDeclaredFunction(); return 0; } void forwardDeclaredFunction() { // Implementation of the function // ... } Forward Declaration for Variables Variables can also be forward declared to inform the compiler about their existence before defining them. Here\u0026rsquo;s an example:\n// Forward declaration for variable extern int globalVar; int main() { globalVar = 42; return 0; } int globalVar; // Actual variable definition Forward Declaration for Namespaces Forward declaration for namespaces can be helpful when dealing with nested namespaces or avoiding circular dependencies. For example:\n// Forward declaration for a namespace namespace MyNamespace; int main() { MyNamespace::someFunction(); return 0; } namespace MyNamespace { void someFunction() { // Implementation } } Forward Declaration for Class Templates You can forward declare class templates when you want to declare them before providing their specializations. Here\u0026rsquo;s an example:\n// Forward declaration for a class template template \u0026lt;typename T\u0026gt; class ForwardDeclaredTemplate; int main() { ForwardDeclaredTemplate\u0026lt;int\u0026gt; instance; return 0; } template \u0026lt;typename T\u0026gt; class ForwardDeclaredTemplate { // Implementation of the template class // ... }; Forward Declaration for Friend Functions When you declare friend functions inside a class, you can forward declare them to separate their declaration from their implementation:\nclass MyClass { public: friend void forwardDeclaredFriendFunction(); }; void forwardDeclaredFriendFunction() { // Implementation } int main() { forwardDeclaredFriendFunction(); return 0; } Benefits of Forward Declaration Forward declaration is beneficial for several reasons:\nCircular Dependencies: It helps resolve circular dependencies between classes and structs, allowing you to create interdependent types. Compile Time Efficiency: It can improve compile time efficiency by reducing the need to include unnecessary header files when you only need a type\u0026rsquo;s declaration. Cleaner Code: It results in cleaner and more modular code by separating the declaration and definition of types. However, excessive use of forward declarations should be avoided, as it can make your code harder to understand and maintain. Use them when necessary to break circular dependencies and improve compilation times.\nConclusion In conclusion, forward declaration is a valuable tool in C++ for managing dependencies between classes, structs, enums and much more. It allows you to declare a type before defining it, helping you resolve circular dependencies and optimize code compilation. Understanding when and how to use forward declaration is essential for writing clean and efficient C++ code.\n","tags":["C++"],"title":"Forward Declaration in C++"},{"categories":["Blog"],"date":"September 22, 2023","permalink":"https://agrawalsuneet.github.io/blogs/enum-vs-enum-class-in-c++/","section":"blogs","summary":"In C++, enumerations (enums) are a powerful tool for creating named sets of integer constants. They help improve code readability and maintainability by providing meaningful names to numeric values. However, C++ offers two ways to define enums: the traditional enum and the more modern enum class. In this blog, we\u0026rsquo;ll explore the differences between these two options and when to use each with the help of examples.\nTraditional enum The traditional enum in C++ allows you to define a set of named integer constants without restricting their underlying type. This means the values are not encapsulated within a specific scope, leading to potential namespace clashes.\n#include \u0026lt;iostream\u0026gt; enum Color { Red, Green, Blue }; int main() { Color myColor = Red; // ... return 0; } In the example above, Red, Green, and Blue are in the same scope as the surrounding code, which can lead to naming conflicts if similar names exist elsewhere in your program.\nenum class In contrast, C++11 introduced the enum class (also known as a scoped enumeration or strong enum) to address the issues of traditional enums. enum class provides stronger type safety by encapsulating the values within their own scope. This makes it less error-prone and more self-contained.\n#include \u0026lt;iostream\u0026gt; enum class Color { Red, Green, Blue }; int main() { Color myColor = Color::Red; // ... return 0; } In this version, Color::Red, Color::Green, and Color::Blue are scoped within the Color enum class, reducing the chances of naming conflicts.\nDifferences Between enum and enum class While both traditional enum and enum class serve the purpose of defining named sets of integer constants, they differ in several important ways. Understanding these differences is crucial for making an informed choice when deciding which one to use in your code:\nScoping: enum: Enumerators declared using the traditional enum are in the same scope as the surrounding code. This can potentially lead to naming conflicts if similar names exist elsewhere in your program.\n#include \u0026lt;iostream\u0026gt; enum Color { Red, Green, Blue }; int main() { Color myColor = Red; // Enum value is in the same scope. int Green = 42; // Potential naming conflict. std::cout \u0026lt;\u0026lt; myColor \u0026lt;\u0026lt; std::endl; // Prints 0 (Red) return 0; } enum class: Enumerators declared within an enum class are scoped within the enum class itself. This encapsulation prevents naming conflicts, as the enumerators are not in the global scope.\n#include \u0026lt;iostream\u0026gt; enum class Color { Red, Green, Blue }; int main() { Color myColor = Color::Red; // Enum value is scoped. int Green = 42; // No naming conflict. std::cout \u0026lt;\u0026lt; static_cast\u0026lt;int\u0026gt;(myColor) \u0026lt;\u0026lt; std::endl; // Prints 0 (Red) return 0; } Type Safety: enum: Traditional enums do not provide strong type safety. They allow implicit type conversions between the enum type and integral types, which can lead to unexpected behavior.\n#include \u0026lt;iostream\u0026gt; enum Color { Red, Green, Blue }; int main() { Color myColor = Red; int myInt = 1; if (myColor == myInt) { std::cout \u0026lt;\u0026lt; \u0026#34;Colors match!\u0026#34; \u0026lt;\u0026lt; std::endl; // Compiles, but unexpected behavior. } return 0; } enum class: Enum classes offer strong type safety. They do not allow implicit type conversions, helping to prevent unintended assignments or comparisons between different enum types.\n#include \u0026lt;iostream\u0026gt; enum class Color { Red, Green, Blue }; int main() { Color myColor = Color::Red; int myInt = 1; if (myColor == myInt) { std::cout \u0026lt;\u0026lt; \u0026#34;Colors match!\u0026#34; \u0026lt;\u0026lt; std::endl; // Error: no match for \u0026#39;operator==\u0026#39; } return 0; } Underlying Type: enum: By default, traditional enums have an underlying integral type, usually int. You can explicitly specify the underlying type, but it\u0026rsquo;s not mandatory.\n#include \u0026lt;iostream\u0026gt; enum Color { Red, Green, Blue }; int main() { std::cout \u0026lt;\u0026lt; sizeof(Color) \u0026lt;\u0026lt; std::endl; // Size is implementation-dependent. return 0; } enum class: Enum classes require you to specify the underlying type explicitly. This promotes clarity and consistency in your code.\n#include \u0026lt;iostream\u0026gt; enum class Color : char { Red, Green, Blue }; int main() { std::cout \u0026lt;\u0026lt; sizeof(Color) \u0026lt;\u0026lt; std::endl; // Size is guaranteed to be 1 byte (char). return 0; } Enumeration Values: enum: Enumeration values are directly accessible without any scope qualification, potentially leading to ambiguous or conflicting names.\n#include \u0026lt;iostream\u0026gt; enum Day { Sunday, // 0 Monday, // 1 Tuesday, // 2 Wednesday, // 3 Thursday, // 4 Friday, // 5 Saturday // 6 }; int main() { Day today = Monday; int dayValue = today; // Enum value directly used as an integer. std::cout \u0026lt;\u0026lt; dayValue \u0026lt;\u0026lt; std::endl; // Prints 1 return 0; } enum class: Enumeration values require qualification with the enum class name, making it clear and unambiguous when you refer to them.\n#include \u0026lt;iostream\u0026gt; enum class Day { Sunday, // Day::Sunday Monday, // Day::Monday Tuesday, // Day::Tuesday Wednesday, // Day::Wednesday Thursday, // Day::Thursday Friday, // Day::Friday Saturday // Day::Saturday }; int main() { Day today = Day::Monday; // int dayValue = today; // Error: no viable conversion from \u0026#39;Day\u0026#39; to \u0026#39;int\u0026#39;. // std::cout \u0026lt;\u0026lt; dayValue \u0026lt;\u0026lt; std::endl; // Compilation error return 0; } Enum Size: enum: The size of a traditional enum is implementation-dependent, as it is determined by the underlying integral type.\n#include \u0026lt;iostream\u0026gt; enum Planet { Mercury, // 0 Venus, // 1 Earth, // 2 Mars // 3 }; int main() { std::cout \u0026lt;\u0026lt; sizeof(Planet) \u0026lt;\u0026lt; std::endl; // Size is implementation-dependent. return 0; } enum class: The size of an enum class is guaranteed to be the same as the size of its underlying integral type, ensuring consistency across platforms.\n#include \u0026lt;iostream\u0026gt; enum class Month : char { January, // Month::January February, // Month::February March, // Month::March April // Month::April }; int main() { std::cout \u0026lt;\u0026lt; sizeof(Month) \u0026lt;\u0026lt; std::endl; // Size is guaranteed to be 1 byte (char). return 0; } Default Values: enum: Traditional enums can implicitly convert to integers, and uninitialized enum variables typically have an undefined value.\n#include \u0026lt;iostream\u0026gt; enum Mood { Happy, // 0 Sad, // 1 Angry // 2 }; int main() { Mood personMood; // Uninitialized enum variable. std::cout \u0026lt;\u0026lt; personMood \u0026lt;\u0026lt; std::endl; // May contain an undefined value. return 0; } enum class: Enum class variables are not implicitly convertible to integers, and uninitialized enum class variables have a well-defined default value (enum_class_type::first_enumerator).\n#include \u0026lt;iostream\u0026gt; enum class State { On, // State::On Off // State::Off }; int main() { State deviceState; // Uninitialized enum class variable. // std::cout \u0026lt;\u0026lt; static_cast\u0026lt;int\u0026gt;(deviceState) \u0026lt;\u0026lt; std::endl; // Prints 0 (State::On is the default) return 0; } Enum Constants: enum: Enum constants can be defined with any valid integer value, including duplicates and values outside the declared range.\n#include \u0026lt;iostream\u0026gt; enum Direction { North = 1, // Assigned value 1 South = 2, // Assigned value 2 East = 3, // Assigned value 3 West = 1 // Duplicate value (allowed) }; int main() { std::cout \u0026lt;\u0026lt; East \u0026lt;\u0026lt; std::endl; // Prints 1 (duplicate values allowed) return 0; } enum class: Enum class constants are strongly enforced to be unique within the scope and adhere to the underlying type\u0026rsquo;s range.\n#include \u0026lt;iostream\u0026gt; enum class Language : short { English = 1, // Assigned value 1 Spanish = 2, // Assigned value 2 French = 3, // Assigned value 3 German = 1 // Error: duplicate enumerator \u0026#39;Language::German\u0026#39; }; int main() { // std::cout \u0026lt;\u0026lt; static_cast\u0026lt;short\u0026gt;(Language::German) \u0026lt;\u0026lt; std::endl; // Compilation error return 0; } Benefits of enum class Strong Typing: Enum classes offer stronger typing, ensuring that you cannot accidentally mix different enum types or assign arbitrary integer values to them.\nScoped Names: Enum classes encapsulate their values within a specific scope, preventing naming clashes with other parts of your code.\nImproved Code Readability: The use of the scope operator (::) makes it clear which enum the value belongs to, enhancing code readability.\nType Safety: Enum classes provide better type safety by restricting implicit type conversions, making your code less error-prone.\nWhen to Choose Each Use Traditional enum When\u0026hellip; You need backward compatibility with older C++ standards. You want the enumeration values to be in the same scope as the surrounding code. You don\u0026rsquo;t need strong type safety or scoping for the enumeration. Use enum class When\u0026hellip; You are working with C++11 or later versions. You want to avoid naming conflicts and ensure better code organization. You need stronger type safety to prevent unintended assignments or comparisons between different enum types. You value code readability and want to make your intentions explicit. Conclusion Choosing between enum and enum class in C++ depends on your specific requirements and the version of C++ you are using. While traditional enums are still relevant in some scenarios, enum class offers better code organization, type safety, and scoping, making it the preferred choice in modern C++ development. Always consider the context and choose the enum type that best suits your project\u0026rsquo;s needs to write clean and maintainable code.\n","tags":["C++"],"title":"Enum vs Enum Class in C++"},{"categories":["Blog"],"date":"September 21, 2023","permalink":"https://agrawalsuneet.github.io/blogs/let-vs-var-const-in-javascript/","section":"blogs","summary":"JavaScript is a versatile and widely used programming language that offers multiple ways to declare variables, including let, var, and const. Each of these declarations serves a specific purpose and has its own scope and behavior. In this blog post, we\u0026rsquo;ll dive into the differences between let, var, and const in JavaScript with examples to help you understand when and how to use them effectively.\nvar - The Traditional Variable Declaration var is the oldest way to declare variables in JavaScript. Variables declared with var are function-scoped, which means their scope is limited to the function they are declared in or the global scope if declared outside any function.\nExample:\nfunction exampleVar() { var x = 10; if (true) { var x = 20; // This reassigns the outer \u0026#39;x\u0026#39; } console.log(x); // Outputs 20 } In the above example, the if block doesn\u0026rsquo;t create a new scope for x, so it reassigns the outer x to 20.\nlet - Block-Scoped Variables let was introduced in ECMAScript 6 (ES6) to address some of the issues with var. Variables declared with let are block-scoped, meaning they are confined to the block (enclosed by curly braces) in which they are defined.\nExample:\nfunction exampleLet() { let x = 10; if (true) { let x = 20; // This is a separate \u0026#39;x\u0026#39; from the outer one } console.log(x); // Outputs 10 } Here, the inner x is distinct from the outer x, thanks to let\u0026rsquo;s block-level scope.\nconst - Constants const is another ES6 addition that allows you to declare variables that cannot be reassigned after their initial value is set. Like let, const is block-scoped.\nExample:\nfunction exampleConst() { const x = 10; if (true) { const x = 20; // This is a separate \u0026#39;x\u0026#39; from the outer one } console.log(x); // Outputs 10 } In this case, you can\u0026rsquo;t reassign the x variable inside the if block because it was declared as a constant.\nlet vs var vs const : Key Differences Scoping: var: Function-scoped or globally scoped. let: Block-scoped (limited to the block or function they are defined in). const: Block-scoped (like let) and constants (cannot be reassigned). Reassignment: var: Allows reassignment within its scope. let: Allows reassignment within its scope. const: Does not allow reassignment once defined. Hoisting: var: Hoisted to the top of its function or global context. It can be used before it`s declared (but will be undefined). let: Hoisted to the top of its block or function, but not initialized. It results in a ReferenceError if used before declaration. const: Hoisted like let, but also results in a ReferenceError if used before declaration. Usage for Constants: var: Not suitable for declaring constants as it allows reassignment. let: Not suitable for declaring constants as it allows reassignment. const: Ideal for declaring constants that should not be changed. Global Object Property: var: Creates a property on the global object (e.g., window in a browser). let: Does not create a global object property. const: Does not create a global object property. Temporal Dead Zone (TDZ): var: No TDZ; variables are initialized with undefined. let: Has a TDZ; accessing a let variable before declaration results in a ReferenceError. const: Also has a TDZ; accessing a const variable before declaration results in a ReferenceError. Use Cases: var: Used less frequently in modern JavaScript due to its unpredictable scoping behavior. It`s mainly used in legacy codebases. let: Preferred for most variable declarations, especially when reassignment may be required within a block. const: Preferred for declaring constants and values that should remain unchanged. When to Use Each Declaration: Use var sparingly, as it has a global or function scope, which can lead to unintended variable hoisting and potential issues in your code. In modern JavaScript, let and const are often preferred over var. Use let when you need a variable that can be reassigned within the same block or function. It provides more predictable scoping behavior than var. Use const when you want to declare a constant value that should not be reassigned. It\u0026rsquo;s a good practice to use const for values that should remain unchanged throughout your code. Conclusion: Understanding the differences between let, var, and const in JavaScript is crucial for writing clean and maintainable code. By choosing the appropriate declaration based on your needs, you can avoid scope-related bugs and make your code more robust. As JavaScript continues to evolve, let and const have become the preferred choices for variable declarations, with var being used less frequently in modern codebases.\n","tags":["JavaScript"],"title":"Let vs Var vs Const in JavaScript"},{"categories":["Blog"],"date":"September 7, 2023","permalink":"https://agrawalsuneet.github.io/blogs/uproperty-in-unreal/","section":"blogs","summary":"Unreal Engine, renowned for its capabilities in creating visually stunning and highly interactive games and simulations, relies on several core features to achieve its potential. Among these, Unreal Property Specifiers, or UPROPERTY, stand out as a powerful tool for developers.\nWhat is UPROPERTY UPROPERTY is a macro in Unreal Engine that allows developers to define various attributes and behaviors for properties within classes. In this blog post, we\u0026rsquo;ll delve deep into UPROPERTY and explore not only its garbage collection aspects but also its key attributes, serialization, saving game state, editor integration, reflection, networking, replication, and more.\nGarbage Collection with UPROPERTY Unreal Engine\u0026rsquo;s memory management is pivotal for both performance and stability. UPROPERTY plays a vital role in garbage collection, ensuring that objects are properly managed and deallocated when they are no longer needed. Here\u0026rsquo;s an example of using UPROPERTY for garbage collection:\nUPROPERTY(Transient) TArray\u0026lt;AActor*\u0026gt; MyActors; // This array will not be included in garbage collection By marking a property as Transient, Unreal Engine knows not to include it in the garbage collection process, which can be useful for temporary or non-persistent data.\nKey Attributes of UPROPERTY UPROPERTY offers a comprehensive range of key attributes, each designed to fine-tune the behavior of properties within Unreal Engine classes:\nEditAnywhere: Allows the property to be edited in the Unreal Editor. BlueprintReadWrite: Enables read and write access in Blueprints. Replicated: Indicates that the property should be replicated across networked instances. SaveGame: Specifies that the property should be saved and loaded when saving game state. VisibleAnywhere: Makes the property visible but not editable in the Unreal Editor. Category: Organizes properties within the Unreal Editor\u0026rsquo;s property window. Config: Allows properties to be loaded from configuration files. Here\u0026rsquo;s an example demonstrating a combination of these attributes:\nUPROPERTY(EditAnywhere, BlueprintReadWrite, Replicated, SaveGame, VisibleAnywhere, Category = \u0026#34;Player Data\u0026#34;, Config) int32 PlayerScore; Serialization and Saving Game State UPROPERTY plays a pivotal role in serialization, ensuring that game state can be saved and loaded seamlessly. When combined with the SaveGame attribute, properties can be automatically included in save files:\nUCLASS() class UMyGameSave : public USaveGame { GENERATED_BODY() public: UPROPERTY(VisibleAnywhere) int32 PlayerScore; }; Editor Integration Unreal Engine\u0026rsquo;s Editor Integration is one of its strengths. UPROPERTY can be used to expose variables and properties to the Unreal Editor for designers and artists to work with:\nUPROPERTY(EditAnywhere) UTexture2D* MyTexture; This allows for easy tweaking and customization within the editor.\nReflection Reflection in Unreal Engine is the ability to inspect and manipulate an object\u0026rsquo;s properties at runtime. UPROPERTY helps enable reflection by providing metadata that Unreal Engine can use to introspect an object\u0026rsquo;s structure:\nUObject* MyObject = GetSomeObject(); UProperty* MyProperty = FindField\u0026lt;UProperty\u0026gt;(MyObject-\u0026gt;GetClass(), TEXT(\u0026#34;MyProperty\u0026#34;)); This allows you to access and modify properties dynamically.\nNetworking and Replication Multiplayer games rely on networking and replication to ensure that game state is synchronized across clients. UPROPERTY\u0026rsquo;s Replicated attribute helps facilitate this process:\nUPROPERTY(Replicated) FVector PlayerLocation; By marking a property as Replicated, Unreal Engine automatically handles network synchronization.\nConclusion UPROPERTY stands as a fundamental and versatile concept in Unreal Engine, allowing developers to control memory management, expose properties to the editor, manage game state, and support networking and replication. Understanding the rich variety of attributes available for UPROPERTY is essential for crafting efficient and engaging Unreal Engine projects. As you dive deeper into Unreal Engine development, you\u0026rsquo;ll discover UPROPERTY as an invaluable tool for creating dynamic and immersive experiences.\n","tags":["Unreal"],"title":"UPROPERTY in Unreal"},{"categories":["Blog"],"date":"September 6, 2023","permalink":"https://agrawalsuneet.github.io/blogs/fstring-vs-fname-vs-text-in-unreal/","section":"blogs","summary":"Unreal Engine, developed by Epic Games, is a popular game engine that powers many successful video games and interactive experiences. When working with Unreal Engine, you often encounter various data types for handling text and strings, including FString, FName, and Text. In this blog post, we\u0026rsquo;ll dive into these three text-related data types, explore their differences, and provide examples of when to use each one.\nFString FString, short for Fixed String, is a dynamic string type used in Unreal Engine. It is similar to the standard C++ string (std::string) and is the most flexible option for handling text. Here are some key features and examples of FString usage:\nDynamic and mutable: You can change the contents of an FString after its creation.\nFString MyString = \u0026#34;Hello, \u0026#34;; MyString += \u0026#34;Unreal Engine!\u0026#34;; Ideal for text manipulation and formatting: FString is excellent for concatenation, manipulation, and formatting of text during runtime.\nFString PlayerName = \u0026#34;John\u0026#34;; FString Greeting = FString::Printf(TEXT(\u0026#34;Hello, %s!\u0026#34;), *PlayerName); Performance considerations: FString has a small performance overhead compared to FName and Text due to its dynamic nature. Avoid excessive use in performance-critical code.\nFName FName, short for Fixed Name, is a more specialized data type in Unreal Engine. It is primarily used to store and reference names, such as object names, property names, and asset names. Here\u0026rsquo;s why you might want to use FName:\nEfficient memory usage: FName uses a global name table, which reduces memory overhead when storing the same name multiple times.\nFName Firstname = FName(TEXT(\u0026#34;John\u0026#34;)); FName SecondName = FName(TEXT(\u0026#34;John\u0026#34;)); In this example, Firstname and SecondName both reference the same entry in the global name table, saving memory.\nIdeal for identifying assets: When referencing assets like textures or materials, FName can be more efficient than FString or Text.\nUTexture2D* MyTexture = LoadObject\u0026lt;UTexture2D\u0026gt;(nullptr, TEXT(\u0026#34;TextureName\u0026#34;)); Not suitable for dynamic text: FName is immutable and not designed for dynamic text manipulation. Use FString or Text for such purposes.\nText Text is another text-related data type in Unreal Engine that\u0026rsquo;s particularly useful for localization and maintaining text in a human-readable format. Here are some key characteristics and use cases for Text:\nLocalization support: Text supports localization, making it easier to manage multiple languages and translations in your game.\nFText MyLocalizedText = NSLOCTEXT(\u0026#34;MyNamespace\u0026#34;, \u0026#34;MyKey\u0026#34;, \u0026#34;Hello World!\u0026#34;); Immutable and safe: Like FName, Text is immutable, which ensures that text remains consistent and unchanged during runtime.\nGood for user-facing text: Use Text for displaying user interfaces, dialogues, or any text visible to players.\nUTextBlock* TextElement = ...; TextElement-\u0026gt;SetText(MyLocalizedText); Slightly more memory overhead: Text has a slightly higher memory overhead than FName due to its localization support, but it\u0026rsquo;s still more memory-efficient than FString.\nDifferences between FString, FName, and Text Mutability: FString: Mutable and dynamic. You can change its contents after creation. FName: Immutable. Once created, it cannot be modified. Text: Immutable. Text objects are also unchangeable after creation. Memory Overhead: FString: Slightly higher memory overhead due to its dynamic nature. FName: Low memory overhead, as it uses a global name table to reduce redundancy. Text: Slightly higher memory overhead compared to FName, mainly due to localization support. Use Cases: FString: Ideal for dynamic text manipulation, formatting, and any situation where the text content may change during runtime. FName: Best suited for storing and referencing names, particularly for objects, properties, and assets. Not suitable for dynamic text. Text: Designed for user-facing text, localization, and maintaining human-readable text. Ideal for text displayed in the user interface, dialogues, and game content where localization is a concern. Performance: FString: Has a performance cost associated with dynamic memory allocation and deallocation. Use it judiciously in performance-critical code. FName: Offers excellent performance due to its low memory overhead and efficient name lookup. Text: Performs well for user interface elements and localization. While it has some additional overhead compared to FName, it\u0026rsquo;s still an efficient choice for most scenarios. Localization Support: FString: No built-in support for localization. Text should be manually managed for localization. FName: No built-in support for localization; typically used for internal references rather than user-facing text. Text: Designed with localization in mind, making it a strong choice for managing text across different languages. Conclusion Understanding the differences between FString, FName, and Text in Unreal Engine is crucial for efficient game development. Each data type has its unique strengths and weaknesses, making them suitable for specific use cases. To summarize:\nUse FString for dynamic text manipulation and formatting. Use FName for efficient storage of names and references to assets or objects. Use Text for user-facing text, localization, and maintaining human-readable text in a standardized way. By choosing the right data type for the job, you can optimize memory usage and improve the overall performance and maintainability of your Unreal Engine project.\n","tags":["Unreal"],"title":"FString vs FName vs Text in Unreal"},{"categories":["Blog"],"date":"August 18, 2023","permalink":"https://agrawalsuneet.github.io/blogs/nested-function-in-javascript/","section":"blogs","summary":"JavaScript is a versatile and widely used programming language that empowers developers to create interactive and dynamic web applications. One of its powerful features is the ability to define functions within functions, known as nested functions. This concept can be a bit tricky to grasp at first, but once understood, it opens the door to more organized and modular code. In this blog, we\u0026rsquo;ll dive into nested functions in JavaScript, provide examples to illustrate their usage, and explore the benefits they bring to your codebase.\nUnderstanding Nested Functions At its core, a nested function is simply a function defined within another function\u0026rsquo;s body. The inner function has access to the variables and parameters of the outer function, as well as global variables, creating a hierarchical scope chain. This can be particularly useful for encapsulating logic, avoiding global pollution, and improving code organization.\nLet\u0026rsquo;s delve into some examples to better understand the concept.\nBasic Nested Function function outerFunction(x) { function innerFunction(y) { return x + y; } return innerFunction; } const addFive = outerFunction(5); console.log(addFive(3)); // Output: 8 In this example, innerFunction is nested within outerFunction. innerFunction retains access to the x parameter of outerFunction even after outerFunction has completed execution. The returned innerFunction can be invoked later with its own arguments.\nClosure and Private Data function createCounter() { let count = 0; function increment() { count++; console.log(count); } return increment; } const counter = createCounter(); counter(); // Output: 1 counter(); // Output: 2 Here, createCounter creates a closure by returning the increment function. The count variable is enclosed within the scope of createCounter, making it act as private data accessible only by the increment function.\nCallback Functions function fetchData(url, callback) { fetch(url) .then(response =\u0026gt; response.json()) .then(data =\u0026gt; callback(data)) .catch(error =\u0026gt; console.error(error)); } function processData(data) { // Process and use the fetched data console.log(data); } fetchData(\u0026#39;https://api.example.com/data\u0026#39;, processData); In this example, the fetchData function accepts a URL and a callback function. The callback, in this case, is processData, which is a nested function. This pattern allows for more structured code when dealing with asynchronous operations.\nBenefits of Nested Functions Encapsulation: Nested functions help encapsulate logic and data, reducing the chances of polluting the global scope with unnecessary variables. Modularity: By organizing code into nested functions, you can create modular and reusable components, improving code maintainability. Closures: Nested functions often create closures, which enable the inner function to maintain access to the variables of its containing function even after the containing function has finished execution. Information Hiding: You can use nested functions to hide implementation details and expose only the necessary interfaces, enhancing code abstraction. Readability: Properly nested functions enhance the readability of your code by grouping related logic together and making the code flow more intuitive. Conclusion Nested functions are a valuable tool in your JavaScript toolkit. They empower you to create more organized, modular, and efficient code while making use of the language\u0026rsquo;s scoping mechanisms. By understanding and mastering the concept of nested functions, you\u0026rsquo;ll be better equipped to design elegant and maintainable JavaScript applications.\n","tags":["JavaScript"],"title":"Nested Function in JavaScript"},{"categories":["Blog"],"date":"August 17, 2023","permalink":"https://agrawalsuneet.github.io/blogs/date-object-in-javascript/","section":"blogs","summary":"Dates and time are fundamental concepts in programming, essential for tasks ranging from displaying the current date on a webpage to performing complex date calculations. JavaScript offers a powerful Date object that enables developers to work with dates, times, and time zones seamlessly. In this comprehensive guide, we\u0026rsquo;ll explore the Date object in JavaScript, cover its methods and properties, and provide a wide range of examples showcasing various date-related operations and formatting options.\nUnderstanding the Date Object The Date object in JavaScript represents a single moment in time. It offers various methods and properties to manipulate, format, and retrieve date and time information. Let\u0026rsquo;s start with some basic concepts.\nCreating a Date Object To create a Date object, you can use either the new Date() constructor or provide a date string.\nconst currentDate = new Date(); // Current date and time const specificDate = new Date(\u0026#39;2023-08-18T12:00:00\u0026#39;); Getting Date Components The Date object provides methods to retrieve various components of a date, such as year, month, day, hour, minute, and second.\nconst year = currentDate.getFullYear(); const month = currentDate.getMonth(); // Returns 0-based month (0 = January) const day = currentDate.getDate(); const hour = currentDate.getHours(); const minute = currentDate.getMinutes(); const second = currentDate.getSeconds(); Formatting Dates JavaScript provides powerful methods to format dates according to your preferences. Let\u0026rsquo;s explore some formatting options.\nUsing toLocaleString() The toLocaleString() method formats a date based on the user\u0026rsquo;s locale.\nconst formattedDate = currentDate.toLocaleString(); // Based on user\u0026#39;s locale Custom Formatting For custom formatting, you can use libraries like date-fns or moment.js. Here\u0026rsquo;s an example using date-fns.\nimport { format } from \u0026#39;date-fns\u0026#39;; const formattedDate = format(currentDate, \u0026#39;MMMM dd, yyyy\u0026#39;); Output Formats JavaScript provides a variety of methods for formatting dates. Here are some examples:\nconst isoString = currentDate.toISOString(); // ISO 8601 format const shortDate = currentDate.toLocaleDateString(); // Short date (MM/DD/YYYY or DD/MM/YYYY) const longDate = currentDate.toDateString(); // Long date (e.g., Wed Aug 18 2023) const time = currentDate.toTimeString(); // Time (HH:mm:ss) Performing Date Calculations The Date object allows for easy date calculations and manipulation.\nAdding and Subtracting Time const tomorrow = new Date(); tomorrow.setDate(currentDate.getDate() + 1); Calculating Time Difference const pastDate = new Date(\u0026#39;2023-08-15\u0026#39;); const timeDiff = currentDate - pastDate; // Difference in milliseconds Working with Time Zones Handling time zones correctly is crucial when working with dates. The Date object offers methods to work with time zones.\nGetting the UTC Date const utcDate = currentDate.toUTCString(); Converting Time Zones const newYorkTime = currentDate.toLocaleString(\u0026#39;en-US\u0026#39;, { timeZone: \u0026#39;America/New_York\u0026#39; }); Real-world Examples Countdown Timer const targetDate = new Date(\u0026#39;2023-12-31T23:59:59\u0026#39;); const timeRemaining = targetDate - currentDate; const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24)); const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000); console.log(`Time remaining: ${days}d ${hours}h ${minutes}m ${seconds}s`); Event Scheduler const events = [ { name: \u0026#39;Meeting\u0026#39;, date: new Date(\u0026#39;2023-08-25T14:00:00\u0026#39;) }, { name: \u0026#39;Workshop\u0026#39;, date: new Date(\u0026#39;2023-09-10T09:30:00\u0026#39;) }, // Add more events ]; events.forEach(event =\u0026gt; { const timeUntilEvent = event.date - currentDate; console.log(`${event.name} in ${(timeUntilEvent / (1000 * 60 * 60)).toFixed(2)} hours`); }); Conclusion The Date object in JavaScript empowers developers to work with dates and times efficiently. From basic operations like retrieving date components to complex calculations involving time zones, the Date object provides a wide array of functionalities. By mastering the Date object and its methods, you can confidently tackle date-related tasks and create dynamic applications that incorporate accurate and well-formatted dates and times.\n","tags":["JavaScript"],"title":"Date Object in JavaScript"},{"categories":["Blog"],"date":"August 16, 2023","permalink":"https://agrawalsuneet.github.io/blogs/map-vs-object-javascript/","section":"blogs","summary":"In JavaScript, data structures play a vital role in organizing and manipulating data efficiently. Two commonly used data structures for storing key-value pairs are the Map and the Object. While they might seem similar at first glance, each has distinct features and use cases that make them suitable for different scenarios. In this blog post, we\u0026rsquo;ll delve into the Map and Object in JavaScript, providing examples that showcase their strengths and helping you make informed decisions when choosing the right data structure for your specific needs.\nIntroduction to Map and Object Map Overview The Map is a built-in data structure introduced in ECMAScript 6 (ES6) that stores key-value pairs, allowing any data type as keys. It maintains the order of insertion and provides various methods for manipulation and iteration.\nObject Overview The Object is a fundamental data structure in JavaScript used to store and manipulate data as key-value pairs. It\u0026rsquo;s a core component of the language and widely used for various purposes.\nKey Differences and Similarities Syntax and Declaration Maps are created using the Map constructor or the new keyword, while objects are created using literal notation or the Object constructor.\nExample:\n// Map const myMap = new Map(); // Object const myObject = {}; Key Types and Ordering Maps can use any data type as keys, including objects, while object keys are limited to strings and symbols. Additionally, maps maintain the order of key insertion, which can be crucial in certain scenarios.\nExample:\n// Map const myMap = new Map(); const objKey = { key: \u0026#39;value\u0026#39; }; myMap.set(objKey, \u0026#39;data\u0026#39;); // Object const myObject = {}; const objKey = { key: \u0026#39;value\u0026#39; }; myObject[objKey] = \u0026#39;data\u0026#39;; Iteration and Size Maps offer built-in methods for iteration (e.g., forEach, keys, values) and can be directly iterated using for\u0026hellip;of. Objects, on the other hand, require methods like Object.keys() for iteration.\nExample:\n// Map myMap.forEach((value, key) =\u0026gt; { console.log(key, value); }); // Object for (const key in myObject) { if (myObject.hasOwnProperty(key)) { console.log(key, myObject[key]); } } Use Cases and Examples Map Use Cases Maps are particularly useful when:\nOrder of key-value pairs matters. Keys are of different data types or objects. Needing to maintain insertion order. Needing to store additional metadata or attributes. Example:\nconst userPreferences = new Map(); userPreferences.set(\u0026#39;theme\u0026#39;, \u0026#39;dark\u0026#39;); userPreferences.set(\u0026#39;fontSize\u0026#39;, 14); userPreferences.set(\u0026#39;language\u0026#39;, \u0026#39;en\u0026#39;); console.log(userPreferences.get(\u0026#39;theme\u0026#39;)); // Output: dark Object Use Cases Objects are well-suited for:\nStoring simple data structures. Creating dictionaries or associative arrays. Quick access to values using string keys. Example:\nconst dictionary = { apple: \u0026#39;a fruit\u0026#39;, car: \u0026#39;a vehicle\u0026#39;, book: \u0026#39;a written work\u0026#39; }; console.log(dictionary.car); // Output: a vehicle Performance Considerations Lookup and Insertion Complexity Map: Average time complexity for insertion and lookup: O(1)\nObject: Average time complexity for insertion and lookup: O(1)\nMemory Consumption Maps generally consume more memory than objects due to their additional metadata and methods.\nChoosing the Right Data Structure When to Use Maps Use Map when you need:\nOrdered key-value pairs. Non-string keys. Iteration methods. Additional metadata or attributes. When to Use Objects Use objects when you need:\nSimple key-value pairs. Quick access using string keys. No requirement for ordered insertion. Real-world Scenarios Storing User Preferences with a Map\nconst userPreferences = new Map(); userPreferences.set(\u0026#39;theme\u0026#39;, \u0026#39;dark\u0026#39;); userPreferences.set(\u0026#39;fontSize\u0026#39;, 14); userPreferences.set(\u0026#39;language\u0026#39;, \u0026#39;en\u0026#39;); console.log(userPreferences.get(\u0026#39;theme\u0026#39;)); // Output: dark Managing a Dictionary with an Object\nconst dictionary = { apple: \u0026#39;a fruit\u0026#39;, car: \u0026#39;a vehicle\u0026#39;, book: \u0026#39;a written work\u0026#39; }; console.log(dictionary.car); // Output: a vehicle Conclusion Both the Map and Object data structures have their unique strengths and use cases in JavaScript. The choice between them depends on the specific requirements of your application. Consider the type of data you need to store, the order of insertion, and the operations you\u0026rsquo;ll perform frequently. By understanding the differences and similarities between Map and Object, you can make informed decisions that lead to efficient and well-structured JavaScript code.\n","tags":["JavaScript"],"title":"Map vs Object : JavaScript"},{"categories":["Blog"],"date":"August 15, 2023","permalink":"https://agrawalsuneet.github.io/blogs/this-keyword-in-javascript/","section":"blogs","summary":"JavaScript is a versatile and dynamic programming language used extensively for web development. One of its key features is the this keyword, which plays a crucial role in determining the context of function execution. Understanding how this works is essential for writing clean and efficient JavaScript code. In this blog post, we\u0026rsquo;ll dive deep into the this keyword, exploring its behavior and providing detailed examples to clarify its usage.\nUnderstanding this Keyword Global Context When used outside of any function or object, the this keyword refers to the global object. In a web browser environment, it refers to the window object.\nExample:\nconsole.log(this === window); // true Function Context Inside a regular function, this depends on how the function is invoked. It refers to the object that calls the function.\nExample:\nfunction greet() { console.log(\u0026#34;Hello, \u0026#34; + this.name); } const person = { name: \u0026#34;Alice\u0026#34; }; person.greet = greet; person.greet(); // Output: Hello, Alice Object Method Context When a function is a method of an object, this refers to the object itself.\nExample:\nconst car = { brand: \u0026#34;Toyota\u0026#34;, getInfo: function() { console.log(\u0026#34;Brand: \u0026#34; + this.brand); } }; car.getInfo(); // Output: Brand: Toyota Event Handlers Context In event handler functions, this typically refers to the DOM element that triggered the event.\nExample:\ndocument.querySelector(\u0026#39;#myButton\u0026#39;).addEventListener(\u0026#39;click\u0026#39;, function() { console.log(this); // Refers to the button element }); Explicit Binding of this JavaScript provides methods to explicitly set the value of this in a function.\ncall() The call() method invokes a function with a specified this value and arguments provided individually.\nExample:\nfunction introduce(language) { console.log(`I am ${this.name} and I code in ${language}.`); } const person = { name: \u0026#34;Bob\u0026#34; }; introduce.call(person, \u0026#34;JavaScript\u0026#34;); // Output: I am Bob and I code in JavaScript. apply() The apply() method is similar to call(), but it accepts arguments as an array.\nExample:\nconst numbers = [1, 2, 3]; const maxNumber = Math.max.apply(null, numbers); console.log(maxNumber); // Output: 3 bind() The bind() method creates a new function with a specified this value and initial arguments.\nExample:\nfunction logMessage(message) { console.log(this.prefix + message); } const logger = { prefix: \u0026#34;[Info] \u0026#34; }; const logInfo = logMessage.bind(logger); logInfo(\u0026#34;This is an important message.\u0026#34;); // Output: [Info] This is an important message. Arrow Functions and this Arrow functions have a lexical this scope, meaning they inherit the this value from their surrounding context.\nExample:\nconst obj = { name: \u0026#34;Lexi\u0026#34;, greet: function() { setTimeout(() =\u0026gt; { console.log(`Hello from ${this.name}!`); }, 1000); } }; obj.greet(); // Output: Hello from Lexi! (after 1 second) Common Pitfalls and Solutions Losing this in Nested Functions When using nested functions, the inner function may have a different this context. Use techniques like saving this in a variable (self or that) or arrow functions to maintain the correct context.\nExample:\nfunction Counter() { this.count = 0; setInterval(function() { // Incorrect: this.count refers to window.count console.log(this.count); }, 1000); } // Solution using arrow function function Counter() { this.count = 0; setInterval(() =\u0026gt; { console.log(this.count); }, 1000); } Caching this for Callbacks When passing functions as callbacks, this can get lost. Cache the desired this value in a variable before entering the callback function.\nExample:\nfunction fetchData(callback) { const self = this; // Cache the correct \u0026#39;this\u0026#39; setTimeout(function() { callback.call(self, \u0026#34;Data received\u0026#34;); }, 1000); } Real-world Examples Creating an Interactive Dropdown Menu const dropdown = { items: [\u0026#39;Home\u0026#39;, \u0026#39;About\u0026#39;, \u0026#39;Services\u0026#39;], init: function() { const menu = document.getElementById(\u0026#39;dropdown-menu\u0026#39;); menu.addEventListener(\u0026#39;click\u0026#39;, this.showItems.bind(this)); }, showItems: function() { this.items.forEach(item =\u0026gt; { console.log(item); }); } }; dropdown.init(); Building a Simple Object-Oriented System class Person { constructor(name) { this.name = name; } introduce() { console.log(`Hi, I\u0026#39;m ${this.name}.`); } } const alice = new Person(\u0026#39;Alice\u0026#39;); alice.introduce(); // Output: Hi, I\u0026#39;m Alice. Conclusion The this keyword is a powerful tool in JavaScript that determines the context in which a function is executed. By understanding its behavior and using techniques like explicit binding and arrow functions, you can write more effective and maintainable code. Remember the common pitfalls and apply the solutions to ensure smooth execution of your JavaScript programs. As you continue to explore JavaScript, mastering the this keyword will contribute to your proficiency in building dynamic and interactive web applications.\n","tags":["JavaScript"],"title":"This Keyword in JavaScript"},{"categories":["Blog"],"date":"August 14, 2023","permalink":"https://agrawalsuneet.github.io/blogs/drawdebugcylinder-in-unreal/","section":"blogs","summary":"Unreal Engine is renowned for its powerful debugging and visualization tools that aid game developers in creating immersive and visually stunning experiences. One such tool that stands out is DrawDebugCylinder, a function that allows you to draw cylinder-shaped debug lines in your game world. In this blog post, we will dive into the details of DrawDebugCylinder in Unreal Engine using C++, including its function signature, parameter explanation, necessary headers, and real-world examples.\nFunction Signature The DrawDebugCylinder function is a part of the UKismetSystemLibrary class, and its signature is as follows:\nUKismetSystemLibrary::DrawDebugCylinder( UObject* WorldContextObject, FVector Start, FVector End, float Radius, int32 Segments, FLinearColor Color, float Duration, float Thickness ); Let\u0026rsquo;s break down each parameter:\nWorldContextObject: A reference to the current world context, typically obtained through the this pointer in your gameplay code. Start: The starting point of the cylinder in world space. End: The end point of the cylinder in world space. This defines the length of the cylinder. Radius: The radius of the cylinder. Segments: The number of segments used to approximate the cylinder\u0026rsquo;s curved surface. A higher value results in a smoother cylinder. Color: The color of the debug cylinder. Duration: The duration, in seconds, for which the debug cylinder will be visible in the game world. Thickness: The thickness of the lines used to draw the cylinder. Headers to Include To utilize the DrawDebugCylinder function, you need to include the following header files:\n#include \u0026#34;Kismet/KismetSystemLibrary.h\u0026#34; Real-World Examples Drawing a Wireframe Pipe Let\u0026rsquo;s say you\u0026rsquo;re developing a sci-fi game, and you want to visualize a network of pipes connecting different modules. You can use DrawDebugCylinder to draw wireframe cylinders to represent these pipes:\n#include \u0026#34;Kismet/KismetSystemLibrary.h\u0026#34; // ... void AMyGameMode::DrawPipes() { FVector PipeStart = FVector(100, 0, 0); FVector PipeEnd = FVector(0, 100, 0); float PipeRadius = 10.0f; int32 PipeSegments = 12; FLinearColor PipeColor = FLinearColor::Red; float PipeDuration = 10.0f; float PipeThickness = 2.0f; UKismetSystemLibrary::DrawDebugCylinder( this, PipeStart, PipeEnd, PipeRadius, PipeSegments, PipeColor, PipeDuration, PipeThickness ); } Visualizing a Laser Beam In a space-themed game, you might want to visualize a laser beam traveling from a spaceship to a target. You can achieve this by drawing a thin cylinder to represent the laser\u0026rsquo;s path:\n#include \u0026#34;Kismet/KismetSystemLibrary.h\u0026#34; // ... void AMyGameMode::DrawLaserBeam() { FVector LaserStart = Spaceship-\u0026gt;GetActorLocation(); FVector LaserEnd = Target-\u0026gt;GetActorLocation(); float LaserRadius = 1.0f; int32 LaserSegments = 4; FLinearColor LaserColor = FLinearColor::Green; float LaserDuration = 0.1f; float LaserThickness = 0.2f; UKismetSystemLibrary::DrawDebugCylinder( this, LaserStart, LaserEnd, LaserRadius, LaserSegments, LaserColor, LaserDuration, LaserThickness ); } Conclusion The DrawDebugCylinder function in Unreal Engine provides an efficient way to visualize cylindrical shapes in your game world, aiding in debugging and visual design. By understanding its function signature, parameter meanings, necessary headers, and real-world examples, you can leverage this tool to create more engaging and visually appealing games. Whether you\u0026rsquo;re representing pipes, laser beams, or any other cylindrical structures, DrawDebugCylinder is a valuable addition to your Unreal Engine toolkit. Happy coding!\n","tags":["Unreal"],"title":"DrawDebugCylinder in Unreal"},{"categories":["Blog"],"date":"August 12, 2023","permalink":"https://agrawalsuneet.github.io/blogs/drawdebugsphere-in-unreal/","section":"blogs","summary":"Unreal Engine is a powerful and versatile game development framework that empowers developers to create stunning and immersive worlds. When it comes to debugging and visualizing game mechanics, Unreal Engine provides a variety of helpful tools, and one of them is DrawDebugSphere. In this blog post, we\u0026rsquo;ll delve into the details of DrawDebugSphere in Unreal Engine using C++, understand its function signature and parameters, explore the necessary headers to include, and provide real-world examples to showcase its usage.\nUnderstanding DrawDebugSphere DrawDebugSphere is a debugging function in Unreal Engine that allows developers to draw a sphere in the game world to visualize certain aspects of their game. This can be particularly useful for debugging collision detection, AI behavior, or any other gameplay mechanic involving spatial relationships. The function provides a way to create a sphere with specified center, radius, color, and other parameters that aid in visualization.\nFunction Signature The function signature of DrawDebugSphere is as follows:\nvoid UGameplayStatics::DrawDebugSphere( UObject *WorldContextObject, FVector Center, float Radius, int32 Segments, FColor Color, bool PersistentLines, float LifeTime, uint8 DepthPriority, float Thickness ); Now, let\u0026rsquo;s break down each parameter:\nWorldContextObject: A reference to the current world context, typically obtained from the owning actor or component. Center: The center location of the sphere in the game world. Radius: The radius of the sphere. Segments: The number of segments used to approximate the sphere\u0026rsquo;s surface. Color: The color of the sphere. PersistentLines: Whether the sphere\u0026rsquo;s lines should persist between frames. LifeTime: The amount of time the sphere should remain visible, in seconds. DepthPriority: The priority of the sphere\u0026rsquo;s depth in the rendering pipeline. Thickness: The thickness of the lines used to draw the sphere. Headers to Include To use DrawDebugSphere, you need to include the following headers:\n#include \u0026#34;Kismet/GameplayStatics.h\u0026#34; // For UGameplayStatics #include \u0026#34;DrawDebugHelpers.h\u0026#34; // For DrawDebugSphere These headers provide the necessary functions and definitions for working with debugging tools in Unreal Engine.\nReal-World Examples Collision Debugging #include \u0026#34;YourActor.h\u0026#34; // Replace with the appropriate actor header // Inside a member function of YourActor void YourActor::DebugCollisionSphere() { FVector SphereCenter = GetActorLocation(); float SphereRadius = 100.0f; FColor SphereColor = FColor::Red; UGameplayStatics::DrawDebugSphere( this, SphereCenter, SphereRadius, 12, SphereColor, false, 5.0f, 0, 2.0f ); } In this example, we\u0026rsquo;re drawing a red sphere at the actor\u0026rsquo;s location with a radius of 100 units. This can help visualize the collision bounds of the actor during gameplay.\nAI Behavior Visualization #include \u0026#34;YourAIController.h\u0026#34; // Replace with the appropriate AI controller header // Inside a member function of YourAIController void YourAIController::DebugAISphere(FVector TargetLocation) { FVector SphereCenter = GetPawn()-\u0026gt;GetActorLocation(); float SphereRadius = 200.0f; FColor SphereColor = FColor::Green; UGameplayStatics::DrawDebugSphere( this, SphereCenter, SphereRadius, 24, SphereColor, false, 2.0f, 0, 1.0f ); // Draw a line from AI pawn to target location UGameplayStatics::DrawDebugLine( this, SphereCenter, TargetLocation, FColor::Blue, false, 2.0f, 0, 1.0f ); } In this example, we\u0026rsquo;re drawing a green sphere around an AI character to visualize its awareness radius, and a blue line from the AI character to a target location to show its intended movement.\nConclusion Debugging is an essential part of game development, and Unreal Engine\u0026rsquo;s DrawDebugSphere function is a valuable tool that aids in visualizing various aspects of gameplay. By utilizing the function\u0026rsquo;s parameters and including the required headers, developers can create informative visualizations to identify issues and fine-tune game mechanics. The real-world examples provided in this blog post demonstrate how DrawDebugSphere can be used to enhance collision detection and AI behavior visualization. Incorporating these debugging techniques into your Unreal Engine projects can help streamline development and create more polished and engaging games.\nHappy debugging and happy developing!\n","tags":["Unreal"],"title":"DrawDebugSphere in Unreal"},{"categories":["Blog"],"date":"August 10, 2023","permalink":"https://agrawalsuneet.github.io/blogs/drawdebugline-in-unreal/","section":"blogs","summary":"Debug visualization is a crucial aspect of game development, aiding programmers and artists in comprehending the behavior and interactions of various game elements. Unreal Engine offers a suite of debugging tools, and one such tool is the DrawDebugLine function. In this blog, we\u0026rsquo;ll delve into the usage of DrawDebugLine in Unreal Engine using C++, accompanied by illustrative examples.\nWhat is DrawDebugLine? DrawDebugLine is a function provided by Unreal Engine that allows you to draw lines in the game world for debugging purposes. It can be immensely helpful for visualizing paths, directions, collisions, and various other game elements. This function is part of the DrawDebugHelpers class and offers flexibility in specifying the starting and ending points of the line, its color, duration, and whether the line persists or not.\nFunction Signature The function signature of DrawDebugLine is as follows:\nvoid DrawDebugLine( UWorld* InWorld, FVector const\u0026amp; LineStart, FVector const\u0026amp; LineEnd, FColor const\u0026amp; Color, bool bPersistentLines, float LifeTime, uint8 DepthPriority, float Thickness ); Let\u0026rsquo;s break down each parameter:\nInWorld: A pointer to the world context in which the line will be drawn. Typically, you can use GetWorld() to obtain this pointer. LineStart: The starting point of the line in world space. LineEnd: The ending point of the line in world space. Color: The color of the line. You can use FColor to define the color, such as FColor::Red or FColor(255, 0, 0). bPersistentLines: Determines whether the line should persist in the world after it\u0026rsquo;s drawn. Set to true if you want the line to stay visible, or false if it should disappear. LifeTime: The duration for which the line will be visible, in seconds. Use a negative value (e.g., -1) for an indefinite duration. DepthPriority: Specifies the rendering priority of the line. A higher value indicates higher priority. Use values between 0 and 255. Thickness: The thickness of the line. Including the Required Headers To use the DrawDebugLine function, you need to include the appropriate headers in your C++ files. Here are the headers you should include:\n#include \u0026#34;YourGameMode.h\u0026#34; // Include your relevant game mode header #include \u0026#34;YourPlayerController.h\u0026#34; // Include your relevant player controller header #include \u0026#34;DrawDebugHelpers.h\u0026#34; // Include the DrawDebugHelpers header Basic Usage Let\u0026rsquo;s start with a basic example of how to use DrawDebugLine in Unreal Engine. In this example, we\u0026rsquo;ll draw a simple white line from the origin of the world to a specified end point:\n#include \u0026#34;YourGameMode.h\u0026#34; #include \u0026#34;DrawDebugHelpers.h\u0026#34; void AYourGameMode::BeginPlay() { Super::BeginPlay(); FVector Start = FVector(0, 0, 0); // Origin FVector End = FVector(100, 0, 0); // Endpoint FColor Color = FColor::White; // Line color // Draw the debug line DrawDebugLine(GetWorld(), Start, End, Color, false, -1, 0, 5); } In this snippet, we specify the start and end points of the line, its color, and set false for persistence (the line won\u0026rsquo;t persist in the world after it\u0026rsquo;s drawn). The -1 value for duration indicates that the line will stay visible indefinitely, and 0 for thickness sets the line thickness. The 5 value for priority specifies the rendering priority of the line.\nVisualizing Traces DrawDebugLine is particularly useful for visualizing traces, such as raycasts and collision checks. Here\u0026rsquo;s an example of using DrawDebugLine to visualize a raycast in Unreal Engine:\n#include \u0026#34;YourPlayerController.h\u0026#34; #include \u0026#34;DrawDebugHelpers.h\u0026#34; void AYourPlayerController::DoRaycast() { FVector Start = PlayerCameraManager-\u0026gt;GetCameraLocation(); FVector ForwardVector = PlayerCameraManager-\u0026gt;GetCameraRotation().Vector(); FVector End = Start + (ForwardVector * 1000); // Raycast distance FHitResult HitResult; // Perform raycast bool bHit = GetWorld()-\u0026gt;LineTraceSingleByChannel(HitResult, Start, End, ECC_Visibility); FColor Color = bHit ? FColor::Red : FColor::Green; // Draw the raycast line DrawDebugLine(GetWorld(), Start, End, Color, false, -1, 0, 5); } In this example, we perform a raycast from the player\u0026rsquo;s camera location in the forward direction. If the ray hits something, the line will be red; otherwise, it will be green.\nConclusion DrawDebugLine is a powerful debugging tool in Unreal Engine that enables developers to visualize lines and traces within the game world. Whether you\u0026rsquo;re debugging movement paths, collision checks, or any other aspect of your game, DrawDebugLine can provide valuable insights into what\u0026rsquo;s happening behind the scenes. By utilizing this function effectively, you can streamline the development process and create more polished and robust games.\nRemember that debugging is an iterative process, and experimenting with different visualizations can greatly enhance your understanding of your game\u0026rsquo;s mechanics. So, don\u0026rsquo;t hesitate to incorporate DrawDebugLine and other debugging tools into your Unreal Engine projects to gain deeper insights into your game\u0026rsquo;s behavior.\nHappy debugging and happy developing!\n","tags":["Unreal"],"title":"DrawDebugLine in Unreal"},{"categories":["Blog"],"date":"August 8, 2023","permalink":"https://agrawalsuneet.github.io/blogs/set-in-javascript/","section":"blogs","summary":"When it comes to managing collections of unique values in JavaScript, the Set object is a hidden gem that can greatly simplify your code and enhance your data handling. In this blog post, we\u0026rsquo;re going to delve into the world of Sets, explore their features, and provide real-world examples of how you can leverage their power in your JavaScript projects.\nWhat is a Set? A Set is a built-in object in JavaScript that allows you to store unique values of any data type, whether they are primitive values or object references. Unlike arrays, Sets don\u0026rsquo;t allow duplicate values, making them perfect for situations where you need to maintain a list of distinct items.\nCreating a Set You can create a new Set using the Set constructor or by passing an iterable (such as an array) to the constructor. Here\u0026rsquo;s how you can create a Set and add values to it:\n// Creating an empty Set const mySet = new Set(); // Adding values to the Set mySet.add(1); mySet.add(2); mySet.add(3); console.log(mySet); // Output: Set { 1, 2, 3 } Removing Duplicate Elements One of the most common use cases for Sets is removing duplicates from an array. Here\u0026rsquo;s how you can achieve this:\nconst duplicateArray = [1, 2, 2, 3, 4, 4, 5]; const uniqueSet = new Set(duplicateArray); console.log([...uniqueSet]); // Output: [1, 2, 3, 4, 5] Checking Membership Sets provide efficient membership checking. You can use the has() method to determine whether a value exists in the Set:\nconst colors = new Set([\u0026#39;red\u0026#39;, \u0026#39;green\u0026#39;, \u0026#39;blue\u0026#39;]); console.log(colors.has(\u0026#39;green\u0026#39;)); // Output: true console.log(colors.has(\u0026#39;yellow\u0026#39;)); // Output: false Iterating Through a Set You can easily iterate through the elements of a Set using a for\u0026hellip;of loop:\nconst vowels = new Set([\u0026#39;a\u0026#39;, \u0026#39;e\u0026#39;, \u0026#39;i\u0026#39;, \u0026#39;o\u0026#39;, \u0026#39;u\u0026#39;]); for (const vowel of vowels) { console.log(vowel); } // Output: // a // e // i // o // u Set Operations Sets also support various set operations like union, intersection, and difference. Here\u0026rsquo;s a quick example of finding the intersection of two sets:\nconst setA = new Set([1, 2, 3, 4]); const setB = new Set([3, 4, 5, 6]); const intersection = new Set([...setA].filter(value =\u0026gt; setB.has(value))); console.log([...intersection]); // Output: [3, 4] Storing Object References Sets are not limited to primitive values. They can also store object references, making them useful for maintaining unique collections of objects:\nconst user1 = { id: 1, name: \u0026#39;Alice\u0026#39; }; const user2 = { id: 2, name: \u0026#39;Bob\u0026#39; }; const user3 = { id: 3, name: \u0026#39;Charlie\u0026#39; }; const userSet = new Set([user1, user2, user3]); console.log(userSet.has(user2)); // Output: true Conclusion Sets are a powerful addition to JavaScript\u0026rsquo;s array of data structures. Their ability to store unique values, efficient membership checking, and support for set operations make them an invaluable tool for handling collections in a wide range of scenarios. Whether you\u0026rsquo;re removing duplicates, checking for existence, or managing object references, Sets offer a clean and efficient solution that can simplify your code and improve its performance. So, next time you find yourself dealing with a collection of unique values, consider harnessing the magic of Sets in your JavaScript projects.\n","tags":["JavaScript"],"title":"Set in JavaScript"},{"categories":["Blog"],"date":"August 6, 2023","permalink":"https://agrawalsuneet.github.io/blogs/map-in-javascript/","section":"blogs","summary":"In the world of JavaScript, data manipulation is a crucial skill for developers. While arrays and objects are common choices for storing data, the Map data type is a powerful alternative that offers unique advantages. In this blog post, we\u0026rsquo;ll embark on a journey to explore the Map data type, understand its features, and showcase practical examples of how it can be employed to enhance your JavaScript code.\nWhat is a Map? The Map data type is introduced in ECMAScript 6 (ES6) and provides a way to store key-value pairs, where each key is associated with a corresponding value. Unlike objects, Map keys can be of any data type, including objects and functions, and they maintain the order of insertion.\nCreating and Using a Map Creating a Map is simple using the Map constructor, and you can initialize it with an array of key-value pairs. Let\u0026rsquo;s create a Map to store information about people\u0026rsquo;s ages:\n// Creating a Map with key-value pairs const ageMap = new Map([ [\u0026#39;Alice\u0026#39;, 28], [\u0026#39;Bob\u0026#39;, 35], [\u0026#39;Charlie\u0026#39;, 22] ]); console.log(ageMap.get(\u0026#39;Alice\u0026#39;)); // Output: 28 Storing Complex Data Map is particularly useful for storing complex data structures. Consider a scenario where you need to associate user profiles with additional data:\nconst userProfileMap = new Map(); const user1 = { id: 1, name: \u0026#39;Alice\u0026#39; }; const user2 = { id: 2, name: \u0026#39;Bob\u0026#39; }; userProfileMap.set(user1, { role: \u0026#39;admin\u0026#39;, email: \u0026#39;alice@example.com\u0026#39; }); userProfileMap.set(user2, { role: \u0026#39;user\u0026#39;, email: \u0026#39;bob@example.com\u0026#39; }); console.log(userProfileMap.get(user1)); // Output: { role: \u0026#39;admin\u0026#39;, email: \u0026#39;alice@example.com\u0026#39; } Iterating Through a Map Map provides convenient methods for iterating through its entries, keys, or values. Let\u0026rsquo;s loop through the ageMap we created earlier:\nfor (const [name, age] of ageMap) { console.log(`${name} is ${age} years old`); } // Output: // Alice is 28 years old // Bob is 35 years old // Charlie is 22 years old Checking Key Existence You can easily check whether a key exists in a Map using the has() method:\nconsole.log(ageMap.has(\u0026#39;Alice\u0026#39;)); // Output: true console.log(ageMap.has(\u0026#39;Eve\u0026#39;)); // Output: false Deleting Entries Removing entries from a Map can be done using the delete() method:\nageMap.delete(\u0026#39;Bob\u0026#39;); console.log(ageMap.get(\u0026#39;Bob\u0026#39;)); // Output: undefined Size and Clearing The size property allows you to determine the number of entries in a Map. You can also clear all entries from a Map using the clear() method:\nconsole.log(ageMap.size); // Output: 2 ageMap.clear(); console.log(ageMap.size); // Output: 0 Conclusion The Map data type in JavaScript offers a versatile and powerful way to manage key-value pairs, enabling you to store, retrieve, and manipulate data with ease. With support for various data types as keys, ordered insertion, and a range of helpful methods, Map is a valuable tool for scenarios requiring more complex data organization than what objects or arrays can offer. From storing user profiles to managing metadata, the Map data type equips you with the flexibility and efficiency needed to tackle diverse programming challenges. So, don\u0026rsquo;t hesitate to embrace the capabilities of the Map data type and elevate your JavaScript coding skills to new heights.\n","tags":["JavaScript"],"title":"Map in JavaScript"},{"categories":["Blog"],"date":"August 4, 2023","permalink":"https://agrawalsuneet.github.io/blogs/map-function-in-javascript/","section":"blogs","summary":"When it comes to working with arrays in JavaScript, the map() function is a versatile and powerful tool that should not be overlooked. This higher-order function allows you to transform each element of an array and create a new array with the transformed values. In this blog post, we\u0026rsquo;ll dive into the map() function and explore its capabilities with real-world examples.\nSyntax and Basics The basic syntax of the map() function is as follows:\nconst newArray = originalArray.map((element, index, array) =\u0026gt; { // Transform the element and return the new value }); element: The current element being processed in the array. index: The index of the current element. array: The original array being processed. The map() function returns a new array containing the transformed values.\nDoubling Array Elements Let\u0026rsquo;s start with a simple example. Suppose you have an array of numbers and you want to create a new array where each number is doubled. Here\u0026rsquo;s how you can achieve that using the map() function:\nconst numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map((number) =\u0026gt; { return number * 2; }); console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10] Capitalizing Names You can also use the map() function to transform strings. Consider an array of names, and you want to create a new array where each name is capitalized. Here\u0026rsquo;s how you can do it:\nconst names = [\u0026#39;alice\u0026#39;, \u0026#39;bob\u0026#39;, \u0026#39;charlie\u0026#39;]; const capitalizedNames = names.map((name) =\u0026gt; { return name.charAt(0).toUpperCase() + name.slice(1); }); console.log(capitalizedNames); // Output: [\u0026#39;Alice\u0026#39;, \u0026#39;Bob\u0026#39;, \u0026#39;Charlie\u0026#39;] Extracting Data The map() function is also handy for extracting specific data from an array of objects. Let\u0026rsquo;s say you have an array of user objects and you want to create a new array containing only the user ages:\nconst users = [ { name: \u0026#39;Alice\u0026#39;, age: 28 }, { name: \u0026#39;Bob\u0026#39;, age: 35 }, { name: \u0026#39;Charlie\u0026#39;, age: 22 } ]; const userAges = users.map((user) =\u0026gt; { return user.age; }); console.log(userAges); // Output: [28, 35, 22] Complex Transformations The map() function can handle more complex transformations as well. Imagine you have an array of temperatures in Celsius and you want to convert them to Fahrenheit:\nconst celsiusTemperatures = [0, 10, 20, 30]; const fahrenheitTemperatures = celsiusTemperatures.map((celsius) =\u0026gt; { return (celsius * 9/5) + 32; }); console.log(fahrenheitTemperatures); // Output: [32, 50, 68, 86] Working with Index The index parameter can be quite useful if you need to perform operations based on the element\u0026rsquo;s position in the array. Let\u0026rsquo;s create an array of even and odd numbers based on the index:\nconst numbers = [1, 2, 3, 4, 5]; const evenOddArray = numbers.map((number, index) =\u0026gt; { return index % 2 === 0 ? \u0026#39;even\u0026#39; : \u0026#39;odd\u0026#39;; }); console.log(evenOddArray); // Output: [\u0026#39;even\u0026#39;, \u0026#39;odd\u0026#39;, \u0026#39;even\u0026#39;, \u0026#39;odd\u0026#39;, \u0026#39;even\u0026#39;] Conclusion The map() function is a versatile tool in the JavaScript developer\u0026rsquo;s toolbox. It allows you to transform array elements easily, making your code more concise and readable. Whether you\u0026rsquo;re doubling numbers, capitalizing strings, extracting data from objects, or performing complex calculations, the map() function can simplify your tasks and enhance your code\u0026rsquo;s maintainability. So next time you find yourself needing to transform elements in an array, remember the map() function and unlock its potential.\n","tags":["JavaScript"],"title":"Map function in JavaScript"},{"categories":["Blog"],"date":"July 3, 2023","permalink":"https://agrawalsuneet.github.io/blogs/bind-function-in-javascript/","section":"blogs","summary":"JavaScript is a versatile programming language that empowers developers to create dynamic and interactive web applications. To harness its full potential, understanding its various features and functions is crucial. One such powerful function is the bind() function. In this blog, we\u0026rsquo;ll delve into the intricacies of the bind() function in JavaScript, its practical applications, and how it can be effectively utilized in your codebase.\nUnderstanding the bind() Function The bind() function is a method available to all JavaScript functions. It allows you to create a new function that, when invoked, has a specific context (the value of the this keyword) and predefined arguments. In simpler terms, bind() lets you set the value of this and lock in arguments for a function, creating a new function with these fixed values.\nSyntax of the bind() Function: const newFunction = originalFunction.bind(thisArg, arg1, arg2, ...); Examples of bind() in Action Preserving this Context: const person = { name: \u0026#39;John\u0026#39;, greet: function() { console.log(`Hello, I\u0026#39;m ${this.name}`); } }; const greetFunction = person.greet; greetFunction(); // Output: Hello, I\u0026#39;m undefined const boundGreet = person.greet.bind(person); boundGreet(); // Output: Hello, I\u0026#39;m John Creating Partial Functions: function multiply(a, b) { return a * b; } const double = multiply.bind(null, 2); console.log(double(5)); // Output: 10 Event Listeners: const button = document.getElementById(\u0026#39;myButton\u0026#39;); function handleClick(message) { console.log(message); } button.addEventListener(\u0026#39;click\u0026#39;, handleClick.bind(null, \u0026#39;Button clicked!\u0026#39;)); Benefits of Using bind() Avoiding this Confusion: bind() ensures that the correct context (this value) is maintained, preventing common mistakes when working with object methods or event handlers. Creating Reusable Functions: By partially binding arguments, you can create specialized versions of functions that are easy to reuse in various contexts. Functional Programming Techniques: bind() facilitates the creation of curried functions and functional programming patterns, enhancing code readability and maintainability. Conclusion The bind() function is a fundamental tool in a JavaScript developer\u0026rsquo;s arsenal. It enables you to control the context of a function and create new functions with fixed arguments, leading to cleaner and more predictable code. Whether you\u0026rsquo;re handling event listeners, managing object methods, or implementing functional programming concepts, bind() can significantly enhance your coding experience. So, the next time you find yourself struggling with maintaining the right context or crafting reusable functions, remember to harness the power of the bind() function in JavaScript.\n","tags":["JavaScript"],"title":"Bind Function in JavaScript"},{"categories":["Blog"],"date":"July 1, 2023","permalink":"https://agrawalsuneet.github.io/blogs/closures-in-javascript/","section":"blogs","summary":"JavaScript, a language renowned for its versatility, offers a wealth of features that enable developers to create powerful and dynamic applications. Among these features, closures stand as a key concept that can greatly enhance code organization, data privacy, and functionality. In this blog, we\u0026rsquo;ll embark on a journey into the world of closures in JavaScript, unraveling their intricacies through illustrative examples and exploring their practical applications.\nUnderstanding Closures A closure is a remarkable JavaScript concept that allows a function to retain access to variables from its containing (enclosing) scope, even after that scope has finished executing. This unique behavior is pivotal in creating powerful and flexible code constructs.\nTo better grasp this concept, let\u0026rsquo;s delve into some practical examples.\nBasic Closure function outerFunction() { let outerVar = \u0026#39;I am from outer\u0026#39;; function innerFunction() { console.log(outerVar); } return innerFunction; } const closureExample = outerFunction(); closureExample(); // Output: \u0026#34;I am from outer\u0026#34; In this example, innerFunction is defined within outerFunction, forming a closure. Even after outerFunction has executed, innerFunction retains access to the outerVar variable.\nClosures and Private Data function createCounter() { let count = 0; function increment() { count++; console.log(count); } return increment; } const counter = createCounter(); counter(); // Output: 1 counter(); // Output: 2 This example showcases the power of closures in creating private data. The count variable is enclosed within the createCounter function\u0026rsquo;s scope, making it inaccessible from the outside. The returned increment function maintains access to this private count variable, providing a controlled way to manipulate it.\nPractical Use in Event Handling function createButton() { const button = document.createElement(\u0026#39;button\u0026#39;); button.innerText = \u0026#39;Click me\u0026#39;; document.body.appendChild(button); let clickCount = 0; button.addEventListener(\u0026#39;click\u0026#39;, function() { clickCount++; console.log(`Button clicked ${clickCount} times.`); }); } createButton(); In this case, a closure is employed to track the number of times a button is clicked. The event listener function, defined within the createButton function, retains access to the clickCount variable, enabling it to increment and display the click count accurately.\nAdvantages of Closures Data Encapsulation: Closures enable the creation of private variables, enhancing data encapsulation and information hiding. Callback Functions: Closures are widely used in creating callback functions for asynchronous operations, retaining access to variables in the outer scope. Functional Programming: Closures align well with functional programming paradigms, allowing for the creation of higher-order functions and currying. Module Pattern: Closures play a pivotal role in the module pattern, enabling the creation of reusable, modular components. Memory Efficiency: Closures can be memory-efficient, as they only keep the necessary variables in memory for as long as they are needed. Conclusion As we conclude our exploration of closures in JavaScript, it\u0026rsquo;s evident that they offer a powerful tool for creating modular, private, and efficient code. The ability of functions to retain access to their surrounding scope\u0026rsquo;s variables, even after execution, empowers developers to craft elegant solutions to a myriad of programming challenges. By mastering closures, you can unlock a deeper level of JavaScript expertise and build applications that are not only functional but also well-organized and maintainable.\n","tags":["JavaScript"],"title":"Closures in JavaScript"},{"categories":["Blog"],"date":"May 2, 2023","permalink":"https://agrawalsuneet.github.io/blogs/vector-in-java/","section":"blogs","summary":"Vectors are an important data structure in Java programming that are used to store and manipulate collections of elements. A vector is similar to an array, but with some additional features that make it more flexible and convenient to use. In this blog, we will explore the basics of vectors in Java, how they differ from arrays, and how to use them in your programs.\nWhat is a Vector in Java? In Java, a vector is a dynamic array-like data structure that can be resized as needed. It is part of the java.util package and provides a set of methods for adding, removing, and accessing elements. A vector is similar to an array in that it stores a collection of elements in contiguous memory locations, but it differs from an array in several ways:\nA vector can grow or shrink dynamically, whereas an array has a fixed size. A vector can hold elements of any type, whereas an array can only hold elements of a single type. A vector is synchronized, meaning that it is thread-safe, whereas an array is not. Creating a Vector To create a Vector in Java, we need to import the java.util.Vector package. Then we can create an instance of the Vector class using the following syntax:\nVector\u0026lt;String\u0026gt; vector = new Vector(); This creates an empty Vector of Strings. We can also specify an initial capacity for the Vector using the following syntax:\nVector\u0026lt;String\u0026gt; vector = new Vector(10); This creates a Vector of Strings with an initial capacity of 10. If we add more elements to the Vector than its capacity, it will automatically resize itself to accommodate the new elements.\nAdding Elements to a Vector We can add elements to a Vector using the add() method. For example, we can add a String to the Vector as follows:\nvector.add(\u0026#34;Hello\u0026#34;); We can also add multiple elements to the Vector using the addAll() method. For example, we can add an array of Strings to the Vector as follows:\nString[] strings = {\u0026#34;World\u0026#34;, \u0026#34;Java\u0026#34;, \u0026#34;Vector\u0026#34;}; vector.addAll(Arrays.asList(strings)); Accessing Elements in a Vector We can access elements in a Vector using the get() method. For example, we can get the first element in the Vector as follows:\nString firstElement = vector.get(0); We can also use a for-each loop to iterate over all the elements in the Vector. For example:\nfor (String element : vector) { System.out.println(element); } Removing Elements from a Vector We can remove elements from a Vector using the remove() method. For example, we can remove the first element in the Vector as follows:\nvector.remove(0); We can also remove all the elements in the Vector using the clear() method. For example:\nvector.clear(); Other Vector Operations Java\u0026rsquo;s Vector class provides several other useful methods for working with vectors. Here are a few examples:\nsize() - returns the number of elements in the Vector isEmpty() - returns true if the Vector is empty contains() - returns true if the Vector contains a specified element indexOf() - returns the index of the first occurrence of a specified element lastIndexOf() - returns the index of the last occurrence of a specified element Conclusion In summary, a Vector is a dynamic array that can grow or shrink in size as needed. Java provides a built-in Vector class that can be used to implement this data structure. The Vector class provides several useful methods for adding, accessing, and removing elements from the vector. With the Vector class in Java, developers have a powerful tool for manipulating collections of objects.\n","tags":["Java"],"title":"Vector in Java"},{"categories":["Blog"],"date":"May 1, 2023","permalink":"https://agrawalsuneet.github.io/blogs/arraylist-in-java/","section":"blogs","summary":"ArrayList is one of the most commonly used data structures in Java. It provides a dynamic array implementation that allows you to add and remove elements from the list. The size of the ArrayList can also be dynamically changed based on the number of elements added or removed from the list. In this blog, we will dive into the details of ArrayList in Java, how it works, and some examples of how to use it.\nWhat is an ArrayList in Java? ArrayList is a class in the Java collections framework that provides a dynamic array implementation. It is similar to an array in that it stores a collection of elements, but it has several advantages over traditional arrays:\nArrayList can grow or shrink dynamically, unlike arrays that have a fixed size. ArrayList can store any type of object, whereas arrays are restricted to a specific type. In other words, an ArrayList is a resizable array that can store any type of object.\nFeatures of ArrayList Dynamic Size - The size of an ArrayList can be dynamically increased or decreased based on the elements that are added or removed from it. Ordered Collection - An ArrayList is an ordered collection, meaning that the elements in it are stored in a specific order, and the position of each element is maintained. Supports Heterogeneous Objects - Unlike traditional Java arrays, an ArrayList can store different types of objects in the same collection. Allows Duplicate Elements - An ArrayList allows duplicate elements to be stored in it. Random Access - Elements in an ArrayList can be accessed randomly, i.e., you can directly access any element in the ArrayList by its index number. Implements Serializable and Cloneable Interfaces - An ArrayList implements the Serializable and Cloneable interfaces, which allows it to be easily serialized and cloned. Creating an ArrayList To create an ArrayList in Java, you need to import the java.util.ArrayList package and then create an instance of the ArrayList class using the new keyword. Here\u0026rsquo;s an example:\nimport java.util.ArrayList; public class Main { public static void main(String[] args) { // create an ArrayList of strings ArrayList\u0026lt;String\u0026gt; fruits = new ArrayList\u0026lt;String\u0026gt;(); // add some elements to the ArrayList fruits.add(\u0026#34;apple\u0026#34;); fruits.add(\u0026#34;banana\u0026#34;); fruits.add(\u0026#34;orange\u0026#34;); // print the elements of the ArrayList System.out.println(fruits); } } In this example, we create an ArrayList of strings called fruits. We then add three elements to the ArrayList using the add method and print the elements using the println method.\nAccessing Elements in an ArrayList You can access elements in an ArrayList using the get() method, which takes an index as its argument and returns the element at that index. Here\u0026rsquo;s an example:\nimport java.util.ArrayList; public class Main { public static void main(String[] args) { // create an ArrayList of strings ArrayList\u0026lt;String\u0026gt; fruits = new ArrayList\u0026lt;String\u0026gt;(); // add some elements to the ArrayList fruits.add(\u0026#34;apple\u0026#34;); fruits.add(\u0026#34;banana\u0026#34;); fruits.add(\u0026#34;orange\u0026#34;); // get the element at index 1 String secondFruit = fruits.get(1); // print the element System.out.println(secondFruit); } } In this example, we use the get method to retrieve the element at index 1 (which is banana) and assign it to a variable called secondFruit. We then print the value of secondFruit.\nAdding and Removing Elements in ArrayList You can add and remove elements from an ArrayList using the add() and remove() methods. Here is an example of how to add and remove elements:\nimport java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayList\u0026lt;String\u0026gt; list = new ArrayList\u0026lt;String\u0026gt;(); list.add(\u0026#34;Apple\u0026#34;); list.add(\u0026#34;Banana\u0026#34;); list.add(\u0026#34;Orange\u0026#34;); list.add(\u0026#34;Grapes\u0026#34;); System.out.println(list); list.remove(2); System.out.println(list); } } The above code will add Grapes to the end of the ArrayList and print the updated list. It will then remove the element at index 2 (which is Orange) and print the updated list again.\nModifying Elements in an ArrayList You can modify elements in an ArrayList using the set() method, which takes an index and a new value as its arguments and replaces the element at the specified index with the new value. Here\u0026rsquo;s an example:\nimport java.util.ArrayList; public class Main { public static void main(String[] args) { // create an ArrayList of strings ArrayList\u0026lt;String\u0026gt; fruits = new ArrayList\u0026lt;String\u0026gt;(); // add some elements to the ArrayList fruits.add(\u0026#34;apple\u0026#34;); fruits.add(\u0026#34;banana\u0026#34;); fruits.add(\u0026#34;orange\u0026#34;); // set the element at index 1 to \u0026#34;pear\u0026#34; fruits.set(1, \u0026#34;pear\u0026#34;); // print the modified ArrayList System.out.println(fruits); } } In this example, we use the set method to replace the element at index 1 (which is banana) with the value pear. We then print the modified ArrayList.\nArrayList Size The size() method is used to get the number of elements in the ArrayList. Here is an example:\nimport java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayList\u0026lt;String\u0026gt; list = new ArrayList\u0026lt;String\u0026gt;(); list.add(\u0026#34;Apple\u0026#34;); list.add(\u0026#34;Banana\u0026#34;); list.add(\u0026#34;Orange\u0026#34;); int size = list.size(); System.out.println(size); } } The above code will print 3 because there are three elements in the ArrayList.\n","tags":["Java"],"title":"ArrayList in Java"},{"categories":["Blog"],"date":"April 29, 2023","permalink":"https://agrawalsuneet.github.io/blogs/map-implementation-in-java/","section":"blogs","summary":"Java provides a powerful data structure called Map, which is used to store key-value pairs. A Map is a collection of unique keys and their corresponding values, and it provides efficient methods to add, remove, and access elements in constant time.\nIn this blog, we will discuss the implementation of the Map interface in Java and explore some of its useful methods.\nWhat is a Map? A map is used to store key value pairs where each key in a map will be unique.\nMap Interface in Java The Map interface is part of the java.util package and is used to store key-value pairs. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the rest of the collection types. The Map interface provides several methods to manipulate the key-value pairs. Here are some of the most commonly used methods:\nput(key, value): Adds the specified key-value pair to the map. If the key already exists, the old value is replaced by the new value. get(key): Returns the value associated with the specified key, or null if the key is not found. remove(key): Removes the key-value pair with the specified key from the map, if it exists. containsKey(key): Returns true if the map contains the specified key, false otherwise. keySet(): Returns a Set of all the keys in the map. clear(): Removes all the elements from the map. values(): Returns a Collection of all the values in the map. General-Purpose Map Implementations HashMap Implementation HashMap is the most commonly used implementation of the Map interface. It is an unordered collection of key-value pairs and provides constant-time performance for the basic operations, such as get and put. It uses the hash function to compute the hash code of the key, which is then used to find the bucket in which the entry should be stored.\nHere is an example of how to create a HashMap and add elements to it:\n// create a new HashMap HashMap\u0026lt;String, Integer\u0026gt; myMap = new HashMap\u0026lt;\u0026gt;(); // add some key-value pairs to the map myMap.put(\u0026#34;apple\u0026#34;, 1); myMap.put(\u0026#34;banana\u0026#34;, 2); myMap.put(\u0026#34;orange\u0026#34;, 3); // get the value for a specific key Integer value = myMap.get(\u0026#34;banana\u0026#34;); System.out.println(\u0026#34;The value for the key \u0026#39;banana\u0026#39; is: \u0026#34; + value); // remove a key-value pair from the map myMap.remove(\u0026#34;orange\u0026#34;); // iterate over the key-value pairs in the map for (String key : myMap.keySet()) { System.out.println(\u0026#34;Key: \u0026#34; + key + \u0026#34;, Value: \u0026#34; + myMap.get(key)); } TreeMap Implementation TreeMap is a sorted implementation of the Map interface. It maintains the elements in a sorted order based on the natural ordering of the keys or a custom Comparator. It provides logarithmic time performance for the basic operations, such as get and put.\nHere is an example of how to create a TreeMap and add elements to it:\nMap\u0026lt;String, Integer\u0026gt; map = new TreeMap\u0026lt;\u0026gt;(); map.put(\u0026#34;apple\u0026#34;, 1); map.put(\u0026#34;banana\u0026#34;, 2); map.put(\u0026#34;orange\u0026#34;, 3); LinkedHashMap Implementation LinkedHashMap is a hybrid implementation of the Map interface that maintains the elements in the order in which they were inserted. It provides constant-time performance for the basic operations, such as get and put.\nHere is an example of how to create a LinkedHashMap and add elements to it:\nMap\u0026lt;String, Integer\u0026gt; map = new LinkedHashMap\u0026lt;\u0026gt;(); map.put(\u0026#34;apple\u0026#34;, 1); map.put(\u0026#34;banana\u0026#34;, 2); map.put(\u0026#34;orange\u0026#34;, 3); Special-Purpose Map Implementations EnumMap It is more efficient than a regular HashMap when working with Enum keys since it is implemented as an array, which provides O(1) time complexity for accessing and updating values based on an Enum key.\nHere is an example of creating an EnumMap and adding elements to it:\n// Create an EnumMap with Day as the key type and String as the value type EnumMap\u0026lt;Day, String\u0026gt; activities = new EnumMap\u0026lt;Day, String\u0026gt;(Day.class); // Add values to the EnumMap activities.put(Day.MONDAY, \u0026#34;Work\u0026#34;); activities.put(Day.TUESDAY, \u0026#34;Workout\u0026#34;); activities.put(Day.WEDNESDAY, \u0026#34;Work\u0026#34;); activities.put(Day.THURSDAY, \u0026#34;Meetings\u0026#34;); activities.put(Day.FRIDAY, \u0026#34;Work\u0026#34;); activities.put(Day.SATURDAY, \u0026#34;Chores\u0026#34;); activities.put(Day.SUNDAY, \u0026#34;Relax\u0026#34;); // Access values in the EnumMap String activityOnMonday = activities.get(Day.MONDAY); System.out.println(\u0026#34;Activity on Monday: \u0026#34; + activityOnMonday); // Iterate over the values in the EnumMap for (Day day : activities.keySet()) { System.out.println(day + \u0026#34;: \u0026#34; + activities.get(day)); } ConcurrentHashMap ConcurrentHashMap is a thread-safe implementation of the Map interface that allows multiple threads to access and modify the map concurrently. It provides high concurrency and scalability, and it is designed to handle high throughput and low latency.\nHere is an example of how to create a ConcurrentHashMap and add elements to it:\nMap\u0026lt;String, Integer\u0026gt; map = new ConcurrentHashMap\u0026lt;\u0026gt;(); map.put(\u0026#34;apple\u0026#34;, 1); map.put(\u0026#34;banana\u0026#34;, 2); map.put(\u0026#34;orange\u0026#34;, 3); WeakHashMap WeakHashMap is a class in Java that implements the Map interface, similar to HashMap or TreeMap. However, unlike HashMap or TreeMap, WeakHashMap holds weak references to its keys.\nIn a weak reference, an object is considered eligible for garbage collection if there are no strong references to it. In the context of WeakHashMap, this means that if a key is no longer in use by any other part of the program, it can be automatically removed from the WeakHashMap. This makes WeakHashMap useful for cases where you want to associate data with objects that are only temporarily used, such as cached data or event handlers.\nConclusion In conclusion, The Map interface in Java provides a convenient way to store key-value pairs. It has various implementations such as HashMap, TreeMap, LinkedHashMap, and Hashtable, which have their unique features and advantages. If you need a fast, unordered Map, you can use HashMap. If you need an ordered Map, you can use TreeMap or LinkedHashMap. If you need a concurrent Map, you can use ConcurrentHashMap. Finally, if you need to store key-value pairs where the keys are enum constants, you can use EnumMap.\n","tags":["Java"],"title":"Map Implementation in Java"},{"categories":["Blog"],"date":"April 28, 2023","permalink":"https://agrawalsuneet.github.io/blogs/set-implementation-in-java/","section":"blogs","summary":"Set is an interface in Java that represents a collection of unique elements, meaning that no two elements in a set can be the same. Java provides several implementations of Set, each with its own unique features and trade-offs. In this blog post, we will explore the different implementations of Set in Java and their use cases.\nWhat is a Set? A set is a collection of unique elements. This means that each element in a set is distinct from all other elements. Sets are often used in programming to represent a collection of data that does not contain duplicates. For example, a set of names would not contain two elements with the same name.\nSet Interface in Java\u0026gt; The Set interface is part of the java.util package and is used to create a collection of unique elements. It extends the Collection interface and adds the following methods:\nadd(E element): Adds the specified element to the set if it is not already present. remove(Object o): Removes the specified element from the set if it is present. contains(Object o): Returns true if the set contains the specified element. size(): Returns the number of elements in the set. isEmpty(): Returns true if the set contains no elements. clear(): Removes all the elements from the set. iterator(): Returns an iterator over the elements in the set. General-Purpose Set Implementations HashSet Implementation HashSet is the most commonly used implementation of the Set interface. It is based on a hash table and does not maintain any order of the elements. The time complexity of basic operations (add, remove, contains) is O(1). The following code shows how to create a HashSet and perform basic operations on it:\nSet\u0026lt;String\u0026gt; set = new HashSet\u0026lt;\u0026gt;(); set.add(\u0026#34;apple\u0026#34;); set.add(\u0026#34;banana\u0026#34;); set.add(\u0026#34;orange\u0026#34;); System.out.println(set.contains(\u0026#34;apple\u0026#34;)); // true System.out.println(set.contains(\u0026#34;grape\u0026#34;)); // false set.remove(\u0026#34;orange\u0026#34;); System.out.println(set.size()); // 2 set.clear(); System.out.println(set.isEmpty()); // true TreeSet Implementation TreeSet is an implementation of the SortedSet interface that uses a red-black tree data structure. It maintains the elements in ascending order based on their natural ordering (or a Comparator provided at the time of creation). The time complexity of basic operations (add, remove, contains) is O(log n). The following code shows how to create a TreeSet and perform basic operations on it:\nSet\u0026lt;Integer\u0026gt; set = new TreeSet\u0026lt;\u0026gt;(); set.add(5); set.add(3); set.add(8); System.out.println(set.first()); // 3 System.out.println(set.last()); // 8 System.out.println(set.contains(5)); // true set.remove(8); System.out.println(set.size()); // 2 LinkedHashSet Implementation LinkedHashSet is an implementation of the Set interface that maintains the insertion order of elements. It is implemented as a hash table with a linked list running through it, so it provides the efficiency of HashSet along with the ordered traversal of elements. The time complexity of basic operations (add, remove, contains) is O(1). The following code shows how to create a LinkedHashSet and perform basic operations on it:\nSet\u0026lt;String\u0026gt; set = new LinkedHashSet\u0026lt;\u0026gt;(); set.add(\u0026#34;apple\u0026#34;); set.add(\u0026#34;banana\u0026#34;); set.add(\u0026#34;orange\u0026#34;); System.out.println(set); // [apple, banana, orange] set.remove(\u0026#34;banana\u0026#34;); System.out.println(set); // [apple, orange] Special-Purpose Set Implementations EnumSet EnumSet is a specialized implementation of Set that is designed to work with enum types. It is highly efficient and provides constant time performance for basic operations such as add, remove, contains, and size. EnumSet uses bit vectors to represent the elements and provides a compact and efficient representation for sets of enum values.\nHere is an example of creating an EnumSet and adding elements to it:\nenum Fruit { APPLE, BANANA, ORANGE } Set\u0026lt;Fruit\u0026gt; set = EnumSet.of(Fruit.APPLE, Fruit.BANANA); ConcurrentSkipListSet ConcurrentSkipListSet is a thread-safe implementation of Set that is optimized for concurrent access. It uses a skip list data structure to store the elements and provides log(n) time performance for basic operations such as add, remove, contains, and size. ConcurrentSkipListSet is well-suited for multi-threaded applications where multiple threads need to access the set concurrently.\nHere is an example of creating a ConcurrentSkipListSet and adding elements to it:\nSet\u0026lt;String\u0026gt; set = new ConcurrentSkipListSet\u0026lt;\u0026gt;(); set.add(\u0026#34;apple\u0026#34;); set.add(\u0026#34;banana\u0026#34;); set.add(\u0026#34;orange\u0026#34;); CopyOnWriteArraySet CopyOnWriteArraySet is a thread-safe implementation of the Set interface in Java, which means that it can be accessed and modified by multiple threads concurrently without any synchronization issues. This implementation is based on the Copy-on-write (COW) technique, which means that any modification operation on the Set creates a new copy of the underlying data structure, which can be modified without affecting the original set.\nIn other words, when an element is added, removed, or replaced in the set, a new copy of the entire set is created, and the modification is made to the new copy, leaving the original set unchanged. This ensures that any ongoing read operations on the original set are not affected by the modification, and they can continue to access the old data.\nConclusion In conclusion, the Set interface in Java provides a convenient way to store a collection of unique elements. The three most commonly used implementations of the Set interface are HashSet, TreeSet, and LinkedHashSet. HashSet provides constant time performance for basic operations, TreeSet maintains elements in ascending order, and LinkedHashSet maintains the insertion order of elements.\n","tags":["Java"],"title":"Set Implementation in Java"},{"categories":["Blog"],"date":"April 27, 2023","permalink":"https://agrawalsuneet.github.io/blogs/function-expression-javascript/","section":"blogs","summary":"JavaScript is a dynamic and versatile programming language that allows developers to create complex and dynamic applications. One of the key features of JavaScript is its ability to use functions as first-class citizens. This means that functions can be assigned to variables, passed as arguments to other functions, and even returned as values from functions. In this article, we\u0026rsquo;ll take a closer look at function expressions in JavaScript and explore how they can be used in your code.\nFunction Expressions A function expression is a type of function that is defined as part of an expression. In other words, it\u0026rsquo;s a function that is defined on the fly, rather than being defined in advance as a named function. Here\u0026rsquo;s an example of a function expression:\nlet multiply = function(a, b) { return a * b; } In this example, we\u0026rsquo;ve created a function expression that takes two arguments, a and b, and returns their product. We\u0026rsquo;ve assigned this function expression to a variable called multiply. This means that we can call the multiply function just like we would any other function:\nlet result = multiply(5, 10); console.log(result); // Output: 50 As you can see, we\u0026rsquo;ve passed the values 5 and 10 as arguments to the multiply function, and it has returned their product, 50.\nAnonymous Function One of the advantages of using function expressions is that they can be anonymous. This means that you don\u0026rsquo;t have to give them a name, which can be useful in certain situations. For example, if you want to create a function that you\u0026rsquo;ll only use once, you can define it as an anonymous function expression:\nlet result = (function(a, b) { return a * b; })(5, 10); console.log(result); // Output: 50 In this example, we\u0026rsquo;ve defined an anonymous function expression that takes two arguments, a and b, and returns their product. We\u0026rsquo;ve then immediately called this function expression with the values 5 and 10. The result of the function is assigned to a variable called result, which is then logged to the console.\nFunction as Arguments Another advantage of using function expressions is that they can be used as arguments to other functions. For example, the Array.prototype.map() method takes a function as an argument and applies it to each element in an array. Here\u0026rsquo;s an example of how you can use a function expression with Array.prototype.map():\nlet numbers = [1, 2, 3, 4, 5]; let doubled = numbers.map(function(number) { return number * 2; }); console.log(doubled); // Output: [2, 4, 6, 8, 10] In this example, we\u0026rsquo;ve defined a function expression that takes a single argument, number, and returns its product by 2. We\u0026rsquo;ve then passed this function expression as an argument to the Array.prototype.map() method, which applies the function to each element in the numbers array and returns a new array with the results.\nConclusion Function expressions are a powerful tool in JavaScript that allows you to define functions on the fly and use them as first-class citizens. They can be assigned to variables, passed as arguments to other functions, and even returned as values from functions.\n","tags":["JavaScript"],"title":"Function Expression : JavaScript"},{"categories":["Blog"],"date":"April 26, 2023","permalink":"https://agrawalsuneet.github.io/blogs/javascript-for-loop/","section":"blogs","summary":"Loops are an essential part of any programming language, and JavaScript is no exception. One of the most common loops used in JavaScript is the for loop. In this blog, we will focus on the for loop in JavaScript and how it can be used to iterate over an array or object.\nWhat is a for loop? A for loop is a programming construct used to repeat a section of code for a specified number of times. The loop consists of three parts:\nInitialization Condition Increment/Decrement The syntax for a for loop in JavaScript is as follows:\nfor (initialization; condition; increment/decrement) { // code to be executed } Let\u0026rsquo;s break down each part of the for loop in more detail.\nInitialization: This is the initial step where we set a variable to a specific value. This part is executed only once before the loop starts. Condition: This is the condition that needs to be met in order for the loop to continue running. If the condition is true, the loop will continue running; if the condition is false, the loop will terminate. Increment/Decrement: This is the step that is executed after each iteration of the loop. It is used to change the value of the variable used in the condition. For Loop Example The code block to be executed is enclosed within curly braces {}. This is where you put the code that you want to repeat.\nfor (let i = 0; i \u0026lt; 10; i++) { console.log(i); } In this example, we are using the for loop to log the numbers from 0 to 9 in the console.\nThe initialization statement sets the value of the variable i to 0. The condition statement checks if i is less than 10. If it is true, the loop will continue. If it is false, the loop will end. The increment statement increments the value of i by 1 after each iteration. For Loop for Arrays The for loop can also be used to iterate through arrays in JavaScript. Here is an example:\nconst fruits = [\u0026#34;apple\u0026#34;, \u0026#34;banana\u0026#34;, \u0026#34;orange\u0026#34;]; for (let i = 0; i \u0026lt; fruits.length; i++) { console.log(fruits[i]); } In this example, we are using the for loop to log each item in the fruits array to the console.\nThe initialization statement sets the value of the variable i to 0. The condition statement checks if i is less than the length of the fruits array. If it is true, the loop will continue. If it is false, the loop will end. The increment statement increments the value of i by 1 after each iteration. For Loop for Objects The for loop can also be used to iterate through objects in JavaScript. However, unlike arrays, objects do not have a length property. Therefore, we need to use the Object.keys() method to get an array of the object\u0026rsquo;s keys, which we can then iterate through using a for loop. Here is an example:\nconst person = { name: \u0026#34;John\u0026#34;, age: 30, occupation: \u0026#34;developer\u0026#34; }; for (let key of Object.keys(person)) { console.log(key + \u0026#34;: \u0026#34; + person[key]); } In this example, we are using the for loop to log each key-value pair of the person object to the console.\nWe are using the Object.keys() method to get an array of the person object\u0026rsquo;s keys. We are then using a for...of loop to iterate through the array of keys. Inside the loop, we are using the key variable to access the value of each key in the person object. ","tags":["JavaScript"],"title":"JavaScript ‘For’ Loop"},{"categories":["Blog"],"date":"April 25, 2023","permalink":"https://agrawalsuneet.github.io/blogs/array-operations-in-javascript-push-pop-shift-unshift/","section":"blogs","summary":"JavaScript is a powerful programming language that offers several ways to manipulate arrays, which are one of the most commonly used data structures in JavaScript. Four important array manipulation methods are push, pop, shift, and unshift. These methods allow you to add and remove elements from the beginning or end of an array. In this blog, we will discuss these methods and their usage in JavaScript.\nPush Method in JS The push() method is used to add one or more elements to the end of an array. It takes one or more arguments, which are the elements that you want to add to the array. The push() method modifies the original array and returns the new length of the array.\nFor example:\nlet myArray = [1, 2, 3]; myArray.push(4); console.log(myArray); // [1, 2, 3, 4] In the above example, we have an array of three elements. We then use the push() method to add a fourth element to the end of the array. The resulting array now has four elements.\nPop Method in JS The pop() method is used to remove the last element from an array. It takes no arguments and modifies the original array. The pop() method returns the removed element.\nFor example:\nlet myArray = [1, 2, 3]; let removedElement = myArray.pop(); console.log(removedElement); // 3 console.log(myArray); // [1, 2] In the above example, we first declare an array of three elements. We then use the pop() method to remove the last element from the array. The removed element is stored in the removedElement variable, and the resulting array has two elements.\nShift Method in JS The shift() method is used to remove the first element from an array. It takes no arguments and modifies the original array. The shift() method returns the removed element.\nFor example:\nlet myArray = [1, 2, 3]; let removedElement = myArray.shift(); console.log(removedElement); // 1 console.log(myArray); // [2, 3] In the above example, we first declare an array of three elements. We then use the shift() method to remove the first element from the array. The removed element is stored in the removedElement variable, and the resulting array has two elements.\nUnshift Method in JS The unshift() method is used to add one or more elements to the beginning of an array. It takes one or more arguments, which are the elements that you want to add to the array. The unshift() method modifies the original array and returns the new length of the array.\nFor example:\nlet myArray = [1, 2, 3]; myArray.unshift(0); console.log(myArray); // [0, 1, 2, 3] In the above example, we have an array of three elements. We then use the unshift() method to add a fourth element to the beginning of the array. The resulting array now has four elements.\nConclusion In this blog, we have discussed the push, pop, shift, and unshift methods in JavaScript. These methods are important for manipulating arrays and are commonly used in JavaScript programming.\nThe push() method is used to add one or more elements to the end of an array The pop() method is used to remove the last element from an array The shift() method is used to remove the first element from an array The unshift() method is used to add one or more elements to the beginning of an array ","tags":["JavaScript"],"title":"Array Operations in JavaScript (Push, Pop, Shift and Unshift)"},{"categories":["Blog"],"date":"April 24, 2023","permalink":"https://agrawalsuneet.github.io/blogs/destructuring-declarations-in-kotlin/","section":"blogs","summary":"Sometimes it\u0026rsquo;s easy to destructure an object into multiple variables of different properties instead of calling it again and again using . operator on the property or instance itself. It is beneficial for a few reasons like,\nWe don\u0026rsquo;t have to use the dot property on the object again and again. If the object is of a nullable type, we can do the null check only once and then we can destructure it to non-nullable properties. The defined variable will be alive within the defined scope. Fewer chances of confusion and more readability. What is destructuring declaration? Let\u0026rsquo;s try to understand what is a destructuring declaration and how does it works internally.\nUsually, when we declare a property, we can initialise it with some value or mark it nullable. If we want to extract a property from an object, we need to do that for each and every property, individually.\nKotlin provides functionality to do that in a single declaration where we can destructure the object into multiple variables within a single declaration.\ndata class Employee (val name : String, val age: Int, val department: String) var employee = Employee(name = \u0026#34;Suneet\u0026#34;, age = 29, department = \u0026#34;Engineering\u0026#34;) var (name, age, department) = employee println(\u0026#34;$name at the age of $age is working in $department department\u0026#34;) The output for the above print statement would be Suneet at the age of 29 is working in Engineering department How does it works internally? The compiler internally uses the componentN function of Kotlin to destructure the object and assign them to the properties individually.\ncomponentN is a functionality provided by Kotlin for any data class which return the Nth property (in sequence from the beginning) of that data class.\nvar (name, age, department) = employee // is equivalent to var name = employee.component1() var age = employee.component2() var department = employee.component3() Things to keep in mind while using destructuring declaration Since we don\u0026rsquo;t use componentN function directly in the destructuring declaration, we can\u0026rsquo;t skip any property. If we don\u0026rsquo;t need any property to be used, the compiler will still extract it but we can avoid it by replacing it with an underscore ( _ ) but we can\u0026rsquo;t skip it.\nvar (name, _, department) = employee Use cases of destructuring declaration Destructuring declaration can be used anywhere but will try to list its common use cases where it can be way more useful and the readability would be better.\n1. Normal Flow Destructuring declaration can be used in any normal flow where an object\u0026rsquo;s properties need to be accessed multiple times.\nvar employee = Employee(name = \u0026#34;Suneet\u0026#34;, age = 29, department = \u0026#34;Engineering\u0026#34;) var (name, age, department) = employee println(\u0026#34;$name at the age of $age is working in $department department\u0026#34;) 2. For-In loop Destructuring declaration can also be used with for-in loops. Instead of declaring the item while iteration, we can directly destructure them to variables and use them inside the loop.\nval list = listOf(Employee(name = \u0026#34;Suneet\u0026#34;, age = 29, department = \u0026#34;Engineering\u0026#34;), Employee(name = \u0026#34;John\u0026#34;, age = 40, department = \u0026#34;Marketing\u0026#34;), Employee(name = \u0026#34;Agrawal\u0026#34;, age = 35, department = \u0026#34;Sales\u0026#34;)) for ((name, age, department) in list){ println(\u0026#34;$name at the age of $age is working in $department department\u0026#34;) } 3. Return from functions Destructuring declaration is also helpful while returning multiple values from a function. Instead of getting the result into a variable and that accessing its individual properties, we can directly destructure it to individual properties.\nfun getBestEmployee(): Employee { //do some calculations return Employee(name = \u0026#34;Suneet\u0026#34;, age = 29, department = \u0026#34;Engineering\u0026#34;) } val (name, age, department) = getBestEmployee() println(\u0026#34;The best Employee is $name\u0026#34;) Keep in mind we can use Pair or Triple also but it\u0026rsquo;s better to have a named variable instead of Pair and Triple as that uses first, second and third as variable names.\n4. In Maps Destructuring declaration can further be used with maps where each entry can be destructured into a key and a value where both can be used directly.\nval map = mapOf(1 to \u0026#34;one\u0026#34;, 2 to \u0026#34;two\u0026#34;, 3 to \u0026#34;three\u0026#34;) for ((key, value) in map){ println(\u0026#34;$key is pointing to $value\u0026#34;) } ","tags":["Kotlin"],"title":"Destructuring Declarations in Kotlin"},{"categories":["Blog"],"date":"April 24, 2023","permalink":"https://agrawalsuneet.github.io/blogs/equality-in-javascript/","section":"blogs","summary":"In JavaScript, there are three types of equality operators: =, ==, and ===. Each of these operators has a different purpose and can lead to different results when used. Understanding the differences between these operators is essential for writing efficient and reliable code in JavaScript.\n= Operator in JS The = operator is used for assigning values to variables. It is called the assignment operator. When using the = operator, the value on the right side of the operator is assigned to the variable on the left side.\nFor example: var x = 5; This assigns the value of 5 to the variable x.\n== Operator in JS The == operator is used for checking equality between two values. It is called the loose equality operator. When using the == operator, JavaScript performs type coercion to compare the values. Type coercion is the process of converting one data type to another data type.\nFor example:\nconsole.log(5 == \u0026#39;5\u0026#39;); // true Here, the == operator compares the values 5 and '5'. Even though they are of different data types (one is a number and the other is a string), JavaScript performs type coercion and returns true.\n=== Operator in JS The === operator is used for checking strict equality between two values. It is called the strict equality operator. When using the === operator, JavaScript compares the values and their data types. If the values and data types are the same, the operator returns true. If the values or data types are different, the operator returns false.\nFor example:\nconsole.log(5 === \u0026#39;5\u0026#39;); // false Here, the === operator compares the values 5 and '5'. Since they are of different data types, JavaScript returns false.\nWhen to use which operator? It is recommended to use the === operator whenever possible because it ensures strict equality checking and avoids unexpected results due to type coercion. The == operator can be used when type coercion is needed or when comparing values of the same data type. The = operator is used for assigning values to variables and should not be confused with the equality operators. Conclusion In conclusion, understanding the differences between the =, ==, and === operators in JavaScript is essential for writing reliable and efficient code. The = operator is used for assignment, the == operator is used for loose equality checking, and the === operator is used for strict equality checking.\n","tags":["JavaScript"],"title":"Equality ('=' vs '==' vs '===') in JavaScript"},{"categories":["Blog"],"date":"April 22, 2023","permalink":"https://agrawalsuneet.github.io/blogs/nested-class-vs-inner-class-kotlin/","section":"blogs","summary":"Nested and Inner classes are two important concepts in Kotlin that allow developers to organize and structure their code in a more effective way. In this blog, we\u0026rsquo;ll explore these concepts and understand how they can be used in Kotlin.\nNested Classes A nested class is a class that is defined inside another class. It is also known as a static inner class, as it is not tied to any specific instance of the outer class. This means that a nested class can be accessed without creating an instance of the outer class.\nTo define a nested class in Kotlin, we use the class keyword inside the body of the outer class.\nFor Example, to defined a nested class called NestedClass inside the OuterClass,\nclass OuterClass { class NestedClass { fun doSomething(){ //I\u0026#39;ll do something } } } Note that the nested class cannot access the properties and methods of the outer class directly.\nclass OuterClass { private val outerProperty = \u0026#34;Outer property\u0026#34; class NestedClass { fun printOuterProperty() { \u0026lt;e\u0026gt;// This won\u0026#39;t compile because the nested class cannot access the outer property\u0026lt;/e\u0026gt; // println(outerProperty) } } } If we try to access the outerProperty inside the printOuterProperty() method, it will result in a compilation error.\nInner Classes An inner class is a class that is defined inside another class, but it has access to the properties and methods of the outer class. This means that an instance of the inner class is tied to an instance of the outer class. In Kotlin, we use the inner keyword to define an inner class.\nclass OuterClass { private val outerProperty = \u0026#34;Outer property\u0026#34; inner class InnerClass { fun printOuterProperty() { // We can access the outer property because this is an inner class println(outerProperty) } } } In the example above, we have defined an inner class called InnerClass inside the OuterClass. Note that we have used the inner keyword to define the inner class. Inside the printOuterProperty() method, we can access the outerProperty because this is an inner class.\nNested vs Inner Classes The key difference between nested and inner classes is the access to the properties and methods of the outer class. A nested class cannot access the properties and methods of the outer class directly, while an inner class can. Another difference is that a nested class is static, while an inner class is tied to an instance of the outer class. When to use Nested and Inner Classes Nested and inner classes can be used in different scenarios based on their differences. A nested class is useful when we want to group related classes together, but the nested class doesn\u0026rsquo;t need access to the properties and methods of the outer class. On the other hand, an inner class is useful when we want to create a class that is closely related to the outer class and needs access to its properties and methods.\nConclusion A nested class is a class that is defined inside another class and is static, while an inner class is a class that is defined inside another class and has access to its properties and methods. We can use nested classes to group related classes together, while we use inner classes to create classes that are closely related to the outer class.\n","tags":["Kotlin"],"title":"Nested Class vs Inner Class : Kotlin"},{"categories":null,"date":"October 27, 2022","permalink":"https://agrawalsuneet.github.io/personalgamesandapps/echoes/","section":"personalgamesandapps","summary":"","tags":null,"title":"Echoes"},{"categories":null,"date":"October 27, 2022","permalink":"https://agrawalsuneet.github.io/publicappearances/droidcon-london-2022/","section":"publicappearances","summary":"","tags":null,"title":"Speaker at Droidcon London 2022"},{"categories":["Blog"],"date":"June 21, 2022","permalink":"https://agrawalsuneet.github.io/blogs/round-vs-floor-vs-ceil-swift/","section":"blogs","summary":"Rounding up to the nearest Integer value functionality is something required a lot of times. Swift has a few inbuilt functions which can do the rounding up for us but they are a bit confusing. To decide when to use what, we need to understand which rounding function rounds up in which direction and which data types it can round up.\nLet\u0026rsquo;s understand them in detail before comparing.\nBefore reading this blog, keep in mind that -3 is bigger than -4 and -3.5 is bigger than -3.51\nround() round rounds up to the nearest Integer which can be above or below or even equal to the actual value. In the case of a positive number, anything which is equal to or below x.49 will be converted to a lower number ie x.00 whereas anything which is equal to or more than x.5 will be converted to a higher number ie x+1.00 In the case of a negative number, anything which is equal to or below -x.5 will be converted to a lower number ie -x-1.00 whereas anything which is equal to or more than -x.49 will be converted to a higher number ie -x.00 print(round(3.00)) //this will print: 3 print(round(3.49)) //this will print: 3 print(round(3.5)) //this will print: 4 print(round(-3.00)) //this will print: -3 print(round(-3.49)) //this will print: -3 print(round(-3.5)) //this will print: -4 floor() floor rounds up to the nearest Integer which can be equal to or below the actual value. In the case of a positive number, anything between x.01 to x.99 will be converted to a lower number ie x.00 whereas x.00 will remain the same x.00 In the case of a negative number, anything between -x.01 to -x.99 will be converted to a lower number ie -x-1.00 whereas -x.00 will remain the same -x.00 print(floor(3.00)) //this will print: 3 print(floor(3.01)) //this will print: 3 print(floor(3.99)) //this will print: 3 print(floor(-3.00)) //this will print: -3 print(floor(-3.01)) //this will print: -4 print(floor(-3.99)) //this will print: -4 ceil() ceil rounds up to the nearest Integer which can be equal to or above the actual value. In the case of a positive number, anything between x.01 to x.99 will be converted to an upper number ie x+1.00 whereas x.00 will remain the same x.00 In the case of a negative number, anything between -x.01 to -x.99 will be converted to an upper number ie -x.00 whereas -x.00 will remain the same -x.00 print(ceil(3.00)) //this will print: 3 print(ceil(3.01)) //this will print: 4 print(ceil(3.99)) //this will print: 4 print(ceil(-3.00)) //this will print: -3 print(ceil(-3.01)) //this will print: -3 print(ceil(-3.99)) //this will print: -3 Common between round, floor and ceil All three work on both Double as well as on Float. Although they round to the nearest Integer, the output still remains Double in the case of Double and Float in the case of Float. Difference between round, floor and ceil round rounds up to the nearest Integer which can be above, below or equal to the actual value.\nx.0 to x.49 -\u0026gt; x.0 x.5 to x.99 -\u0026gt; x+1.0 -x to -x.49 -\u0026gt; x.0 -x.5 to -x.99 -\u0026gt; -x-1.0 floor rounds up to the nearest Integer which can be equal to or below the actual value.\nx.0 to x.99 -\u0026gt; x.0 -x.01 to -x.99 -\u0026gt; -x-1.0 ceil rounds up to the nearest Integer which can be equal to or above the actual value.\nx.01 to x.99 -\u0026gt; x+1.0 -x.01 to -x.99 -\u0026gt; -x.0 The third digit after decimal doesn\u0026rsquo;t make any difference. ","tags":["Swift"],"title":"Round vs Floor vs Ceil : Swift"},{"categories":["Blog"],"date":"June 18, 2022","permalink":"https://agrawalsuneet.github.io/blogs/safe-calls-vs-nil-checks-in-swift/","section":"blogs","summary":"In Swift, the type system distinguishes between references that can hold nil (nil references) and those that can not (non-nil references).\nFor example, a normal property can’t hold a nil value and will show a compile error.\nvar variable : CustomClass = CustomClass() variable = nil //compilation error //\u0026#39;nil\u0026#39; cannot be assigned to type \u0026#39;CustomClass\u0026#39; Instead, we can add a ? after the data type of that property which declares that variable as a nillable property.\nvar nillableVariable : CustomClass? = CustomClass() nillableVariable = nil //works fine In any case, the nillable property requires a nil check every time before accessing that property or requires a confirmation from the developer that the estimation of that property won’t be nil while accessing it.\nvariable.someMethodCall() //works fine as the compiler is sure that //the variable can’t be nil nillableVariable.someMethodCall() //will highlight compilation error //as compiler is not sure as //nilVariable can be nil. There are still few techniques for using or accessing the nillable variable. One of them is safe call ?. and another one is nil check !. but before figuring out the difference among both, let’s understand what they are in detail first.\nIf Let and Guard Let This is the old pattern that we use in every other language, checking the variable if its nil or not.\nIf let checks if the nillable variable is nil or not.\nIf the variable is nil, this will go to else block.\nIf not, it will copy the non-nil reference into another variable within its scope where we can use it without any nil checks.\nif let nillableVariable = nillableVariable { nillableVariable.someMethodCall() } else { // fallback flow } Guard let separates the failure case first. It is designed to exit the current function, loop or condition if the check fails.\nIt is used to run a code block and return if the variable is nil otherwise below else condition, the variable is non-nil and we can use it without any nil checks.\nguard let nillableVariable = nillableVariable else { //do something in nil case return } nillableVariable.someMethodCall() You can read the difference between if-let and guard-let on if vs if let vs guard let in Swift.\nSafe Calls (?.) Another way of using a nillable property is safe call operator ?.\nThis calls the method if the property is not nil or returns nil if that property is nil without throwing an NPE (nil pointer exception).\nnillableVariable?.someMethodCall() Safe calls are useful in chains. For example, if Bob, an Employee, may be assigned to a Department (or not), that in turn may have another Employee as a department head, then to obtain the name of Bob’s department head (if any), we write the following\nlet departmentHead = bob?.department?.head?.name Such a chain returns nil if any of the properties in it is nil.\nNil-Coalescing Operator (??) This one is similar to safe calls except the fact that it can return a non-nil value if the calling property is nil even\nval result = nillableVariable?.someMethodCall() ?? fallbackIfnilMethodCall() The Nil-Coalescing operator will evaluate the left expression and will return it if it’s not nil else will evaluate the right side expression. Please note that the right side expression will only be called if the left side expression is nil.\nThe !. Operator This operator is used to explicitly tell the compiler that the property is not nil and if it’s nil, please throw a nil pointer exception (NPE)\nnillableVariable!.someMethodCall() This code will work fine if ‘nillableVariable’ is not nil else it will throw an NPE.\nDifference between ?. and !. The basic difference while using ?. and !. is if you want to separate a normal flow of var or let property having a ‘non-nil’ value with ‘nil’ value flow use ?. But if you are sure that the property value is not nil use !. instead of ?. Also, ?. can be used to call default flow using ?? at the end of the expression but !! will only throw an NPE. ","tags":["Swift"],"title":"Safe calls(?.) vs Nil checks(!.) in Swift"},{"categories":["Blog"],"date":"June 17, 2022","permalink":"https://agrawalsuneet.github.io/blogs/default-vs-optional-vs-explicit-non-nil-variables-swift/","section":"blogs","summary":"In Swift, we can differentiate the variables into three different categories based on their possible values.\nThe variable can be of default type, optional type or an explicit non-nil type.\nAll three types of variables can be clubbed with both let and var. Or they can also be used with any data type.\nBefore looking at their differences, Let\u0026rsquo;s try to understand them one by one in detail.\nDefault Type Variable Default type variables are the ones which need to be initialised either in the constructor or need to be declared along with the definition itself. It can be initialised with some default value and later can be changed if it\u0026rsquo;s a mutable var type.\nThere is no separate syntax for default type variables.\nIf we don\u0026rsquo;t initialise the variable with definition and even in the constructor, The compiler will show an error.\nclass CustomClass{ var defaultVariable: Int var defaultVariable2: Int = -1 init(defaultVariable : Int){ self.defaultVariable = defaultVariable } } Optional Type Variable Optional type variables are the ones which can hold a nil value as well.\nInitialising the optional type variables is optional at both the places ie while defining or in the constructor.\nBy default, the compiler will initialise the optional variable with a nil value. It can be changed to nil if the variable is of var type.\nOptional variables can be defined using ? as a suffix to the variable type. Option variables require a nil check or unwrapping while using them.\nclass CustomClass{ var optionalVariable: Int? var optionalVariable2: Int? = -1 } Explicit Non-nil Variables Explicit Non-nil variables are the ones which are not required to be initialised while defining the variable as well as in the construct but whenever we are going to use the variable, it will be treated as a non-optional or default type variable.\nThis means we don\u0026rsquo;t have to add any nil check while using this variable.\nIn short, we tell the compiler that it will be the developer\u0026rsquo;s responsibility to initialise the property before using it. If we don\u0026rsquo;t initialise before using it, it will throw an NPE.\nclass CustomClass{ var explicitNonNilVariable: Int! var explicitNonNilVariable2: Int! = -1 } Default vs Optional vs Explicit Non-nil Variables\nA default variable needs to be initialised while defining or in the constructor. There is no need to use a nil check while using the default variable. An optional variable doesn\u0026rsquo;t need to be initialised while defining or in the constructor. This will need a nil check before using it. An explicit non-nil variable doesn\u0026rsquo;t need to be initialised while defining or in the construct but it\u0026rsquo;s the developer\u0026rsquo;s responsibility to make sure that it will be non-nil before accessing it. There is no need to use a nil check while using it as well. ","tags":["Swift"],"title":"Default vs Optional vs Explicit Non-nil Variables: Swift"},{"categories":["Blog"],"date":"June 16, 2022","permalink":"https://agrawalsuneet.github.io/blogs/question-mark-in-swift/","section":"blogs","summary":"In Swift, the question mark works differently in different situations or when clubbed with some other keywords. It sometimes denotes the variable type as optional or sometimes being used for optional chaining.\nLet\u0026rsquo;s try to understand them in detail before looking at their differences.\nOptional Variable ? It makes the variable type optional if added as a suffix to the variable type while defining any variable. It will need a nil check before accessing the optional variable.\nYou can read about the different types of variables in the blog Default vs Optional vs Explicit Non-nil Variables: Swift.\nThe syntax will look like the below for the optional variable.\nvar nullableVariable: Int? Safe Call or Optional Chaining Operator ?. It is used to chain any optional variable or property further to other properties or functional calls.\nSafe calls are useful in chaining. For example, if Bob, an Employee, may be assigned to a Department (or not), that in turn may have another Employee as a department head, then to obtain the name of Bob’s department head (if any), we write the following\nlet departmentHead = bob?.department?.head?.name Such a chain returns nil if any of the properties in it is nil.\nDefault Value ?? The default value is used to provide the default value if the expression before the default value operator is nil.\nFor example in the above example where we were looking for the department head name, if the left expression is nil, we can provide the default value as below.\nlet departmentHead = bob?.department?.head?.name ?? \u0026#34;No department head found\u0026#34; Ternary Operator ? : The ternary operator is used to separate the flows for true and false conditions for a bool variable or condition. We can call functions, assign values or even executes some code block in both true and false conditions.\nThe syntax for the same will look like below.\nlet a = 10 let result = a == 10 ? \u0026#34;Ten\u0026#34; : \u0026#34;Some Other Value\u0026#34; Difference Between ? , ?. , ?? and ? : ? is used to make the variable an optional type. ?. is used for optional chaining. ?? is used to provide the default value. ? : separates the true and false flow for any condition or bool variable. ","tags":["Swift"],"title":"Question Mark (? vs ?. vs ?? vs ? :) in Swift"},{"categories":["Blog"],"date":"June 13, 2022","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-count-function/","section":"blogs","summary":"The collection is something which is used by almost everyone. It makes our life easy. List, Set and Map are the best examples of them.\nTo iterate, filter or modify the existing collection object, Kotlin provides us with a few in builds functions. Count function is one of them.\nLets try to understand the count function in detail.\nWhat is Count function? The count function is used to get the total number of elements in the collection.\nIt can also be used to get the number of elements in the collection that satisfy some condition.\nThe count function has two overloads.\nFirst one takes zero arguments and returns the total elements in the collection.\nOther one takes a higher order function (predicate) as an argument and returns the number of elements in the collection which confirms that predicate.\n/** * Returns the number of elements in this collection. */ @kotlin.internal.InlineOnly public inline fun \u0026lt;T\u0026gt; Collection\u0026lt;T\u0026gt;.count\u0026lt;/b\u0026gt;(): Int { return size } /** * Returns the number of elements matching the given [predicate]. */ public inline fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.count\u0026lt;/b\u0026gt;(predicate: (T) -\u0026gt; Boolean): Int { if (this is Collection \u0026amp;\u0026amp; isEmpty()) return 0 var count = 0 for (element in this) if (predicate(element)) checkCountOverflow(++count) return count } The first overload of count function doesn\u0026rsquo;t take any parameter and it returns the size of the collection. It actually returns the size variable.\nThe second overload take a predicate and returns the count of the elements which satisfy that predicate. The predicate takes every element one by one as a parameter and return a bool type.\nBoth the overloads of count are available in all type of arrays like IntArray, CharArray and many more. They are also available in collection means in List, Set and Map.\nAll the above implements are extension functions which returns the count of elements in that collection conditionally or unconditionally.\nFilter with List count function can be used over a list to get the size of the list. It can also be used to get the count of elements in the list that confirms the condition. The second overload can be used with a named parameter or using it.\nThe code will look like below.\nval list = listOf(1, 2, 3, 4, 5) println(list.count\u0026lt;/b\u0026gt;()) println(list.count\u0026lt;/b\u0026gt; { it % 2 == 0 }) println(list.count\u0026lt;/b\u0026gt; { item -\u0026gt; item % 2 == 0 }) Filter with Set Similar to list, count function can be used over a set to get the size of the set. It can also be used to get the count of elements in the set that confirms the condition. The second overload can be used with a named parameter or using it.\nThe code will look like below.\nval set = setOf(1, 2, 3, 4, 5) println(set.count\u0026lt;/b\u0026gt;()) println(set.count\u0026lt;/b\u0026gt; { it % 2 == 0 }) println(set.count\u0026lt;/b\u0026gt; { item -\u0026gt; item % 2 == 0 }) Filter with Map Similar to list and set, count function can be used over a map to get the size of the map. It can also be used to get the count of elements in the map that confirms the condition. The second overload can be used with a named parameter or using it.\nThe code will look like below.\nval map = mapOf(\u0026#34;key1\u0026#34; to 1, \u0026#34;key2\u0026#34; to 2, \u0026#34;key3\u0026#34; to 3) println(map.count\u0026lt;/b\u0026gt;()) println(map.count\u0026lt;/b\u0026gt; { it.value % 2 == 0 }) println(map.count\u0026lt;/b\u0026gt; { element -\u0026gt; element.value % 2 == 0 }) ","tags":["Kotlin"],"title":"Kotlin Count Function"},{"categories":["Blog"],"date":"May 18, 2022","permalink":"https://agrawalsuneet.github.io/blogs/plus-and-minus-operator-kotlin/","section":"blogs","summary":"The collection is something which is used by almost everyone. It makes our life easy. List, Set and Map are the best examples of them.\nTo iterate, filter or modify the existing collection object, Kotlin provides us with a few in builds transform operators. Plus and Minus operator are few of them of them.\nLets try to understand the plus and minus operator in detail.\nWhat are plus and minus operator? Plus operator is used to creating a new collection object by adding an element or a list of elements to the existing one.\nKeep in mind that the returned collection object is read-only or val type.\nThe values that need to be added, can be passed as single element or a list or collection of elements.\nThe type alias for plus function is +\nMinus operator is used to creating a new collection object by removing an element or a list of elements to the existing one.\nKeep in mind that the returned collection object is read only or val type.\nThe values that need to be removed, can be passed as single element or a list or collection of elements.\nBut, in case of minus, if the item which is subtracted is just a single element, it will just remove its first occurrence but if we remove by passing it in a collection, it will remove all the occurrence of that element.\nThe type alias for minus function is -\n/** * Returns a list containing all elements of the original collection and then all elements of the given [elements] array. */ public operator fun \u0026lt;T\u0026gt; Collection\u0026lt;T\u0026gt;.plus(elements: Array\u0026lt;out T\u0026gt;): List\u0026lt;T\u0026gt; { val result = ArrayList\u0026lt;T\u0026gt;(this.size + elements.size) result.addAll(this) result.addAll(elements) return result } /** * Returns a list containing all elements of the original collection and then all elements of the given [elements] collection. */ public operator fun \u0026lt;T\u0026gt; Collection\u0026lt;T\u0026gt;.plus(elements: Iterable\u0026lt;T\u0026gt;): List\u0026lt;T\u0026gt; { if (elements is Collection) { val result = ArrayList\u0026lt;T\u0026gt;(this.size + elements.size) result.addAll(this) result.addAll(elements) return result } else { val result = ArrayList\u0026lt;T\u0026gt;(this) result.addAll(elements) return result } } /** * Returns a list containing all elements of the original collection without the first occurrence of the given [element]. */ public operator fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.minus(element: T): List\u0026lt;T\u0026gt; { val result = ArrayList\u0026lt;T\u0026gt;(collectionSizeOrDefault(10)) var removed = false return this.filterTo(result) { if (!removed \u0026amp;\u0026amp; it == element) { removed = true; false } else true } } /** * Returns a list containing all elements of the original collection except the elements contained in the given [elements] array. */ public operator fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.minus(elements: Array\u0026lt;out T\u0026gt;): List\u0026lt;T\u0026gt; { if (elements.isEmpty()) return this.toList() val other = elements.convertToSetForSetOperation() return this.filterNot { it in other } } Plus and Minus with List Plus operator adds the elements to the existing list and returns a read-only (val type) list.\nMinus operator removes the element from the existing list and returns a read-only (val-type) list. If we pass a single element, it will only remove its first occurrence but if we pass it as a list, it will remove all the occurrences of the second list elements from the first list.\nval list = listOf(1, 2, 3, 4, 5, 5) println(list + 6) println(list + listOf(6, 7, 8)) println(list - 5) println(list - listOf(5, 6)) Plus and Minus with Set Plus operator adds the elements to the existing set and returns a read-only (val type) set. If the item already exists in the set, it will not change anything but will just convert it to a read-only set.\nMinus operator removes the element from the existing set and returns a read-only (val-type) set. Since all the elements in a set are unique, it doesn\u0026rsquo;t matter if we pass it as a single element or as a set, it will remove them from the existing set.\nval set = setOf(1, 2, 3, 4, 5) println(set + 6) println(set + setOf(6, 7, 8)) println(set - 5) println(set - setOf(5, 6)) Plus and Minus with Map Plus and minus operators work a bit different in the case of map.\nTo plus a single element to the existing map, we can pass it as a Pair.\nIf the item is already there in the map, the plus operator will override its value for that particular key.\nWe can even pass another map to add the key-value pairs. if any of the keys already exist in the map, this will override its value.\nIn the case of minus, since all the keys are unique, it will just remove the key-value pairs from the existing ones.\nval map = mapOf(\u0026#34;key1\u0026#34; to 1, \u0026#34;key2\u0026#34; to 2, \u0026#34;key3\u0026#34; to 3) println(map + Pair(\u0026#34;key4\u0026#34;, 4)) println(map + Pair(\u0026#34;key1\u0026#34;, 100)) println(map + mapOf(\u0026#34;key5\u0026#34; to 5, \u0026#34;key1\u0026#34; to 100)) println(map - \u0026#34;key1\u0026#34;) println(map - listOf(\u0026#34;key1\u0026#34;, \u0026#34;key2\u0026#34;)) ","tags":["Kotlin"],"title":"Plus(+) and Minus(-) Operator : Kotlin"},{"categories":["Blog"],"date":"May 1, 2022","permalink":"https://agrawalsuneet.github.io/blogs/filter-operator-kotlin/","section":"blogs","summary":"The collection is something which is used by almost everyone. It makes our life easy. List, Set and Map are the best examples of them.\nTo iterate, filter or modify the existing collection object, Kotlin provides us with a few in builds transform operators. Filter operator is one of them.\nLets try to understand the filter operator in detail.\nWhat is filter operator? Filter operator is used to create a new collection object by iterating over the existing collection object and filtering the elements based on the predicates to it. The predicate that needs to be checked for, is passed as lambda to the function.\nSince the filter operator is an extension of the Iterable Interface, it can be used with all three collections ie List, Set and Map.\n/** * Returns a list containing only elements matching the given [predicate]. * * @sample samples.collections.Collections.Filtering.filter */ public inline fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.filter(predicate: (T) -\u0026gt; Boolean): List\u0026lt;T\u0026gt; { return filterTo(ArrayList\u0026lt;T\u0026gt;(), predicate) } Filter also has other few functions as below,\nfilterIndexed used for indexed iteration and filter the elements based on the given predicate. filterNot used to filter the elements which did not match the given predicate. filterNotNull used for filtering non-null elements. This doesn\u0026rsquo;t take any predicate. filterIsInstanceused to filter all the elements which are instance of a particular type. This also doesn\u0026rsquo;t take any predicate. /** * Returns a list containing only elements matching the given [predicate]. * @param [predicate] function that takes the index of an element and the element itself * and returns the result of predicate evaluation on the element. * * @sample samples.collections.Collections.Filtering.filterIndexed */ public inline fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.filterIndexed(predicate: (index: Int, T) -\u0026gt; Boolean): List\u0026lt;T\u0026gt; { return filterIndexedTo(ArrayList\u0026lt;T\u0026gt;(), predicate) } /** * Returns a list containing all elements not matching the given [predicate]. * * @sample samples.collections.Collections.Filtering.filter */ public inline fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.filterNot(predicate: (T) -\u0026gt; Boolean): List\u0026lt;T\u0026gt;\u0026gt;{ return filterNotTo(ArrayList\u0026lt;T\u0026gt;(), predicate) } /** * Returns a list containing all elements that are not `null`. * * @sample samples.collections.Collections.Filtering.filterNotNull */ public fun \u0026lt;T : Any\u0026gt; Iterable\u0026lt;T?\u0026gt;.filterNotNull(): List\u0026lt;T\u0026gt; { return filterNotNullTo(ArrayList\u0026lt;T\u0026gt;()) } /** * Returns a list containing all elements that are instances of specified type parameter R. * * @sample samples.collections.Collections.Filtering.filterIsInstance */ public inline fun \u0026lt;reified R\u0026gt; Iterable\u0026lt;*\u0026gt;.filterIsInstance(): List\u0026lt;@kotlin.internal.NoInfer R\u0026gt; { return filterIsInstanceTo(ArrayList\u0026lt;R\u0026gt;()) } Filter with List filter operator can be used over a list to check the predicate on its elements and return the filtered list. It can be used with a named parameter or using it.\nval list = listOf(1, 2, 3, 4, 5) val filteredList = list.filter { it % 2 == 0 } println(filteredList) val filteredList2 = list.filter { item -\u0026gt; item % 2 == 0 } println(filteredList2) val filteredNotList = list.filterNot { item -\u0026gt; item % 2 == 0 } println(filteredNotList) In the case of filterIndexed, since we have two variables passed in the lambda function, we can not skip the named parameters.\nval list = listOf(1, 2, 3, 4, 5) val filteredIndexList = list.filterIndexed {index, item -\u0026gt; (index != 0) \u0026amp;\u0026amp; (item % 2 == 0) } println(filteredIndexList) In the case of filterNotNull, it filter outs the null values and return the list of only the non-null values.\nval list = listOf(1, null, 3, 4, 5, null) val filteredNotNullList = list.filterNotNull() println(filteredNotNullList) In the case of filterIsInstance, it filter outs and return the list of the elements of particular data type specified.\nval list = listOf(1, \u0026#34;\u0026#34;, true, 4, 0.0, 0.0f) val filteredIsInstanceList = list.filterIsInstance\u0026lt;Int\u0026gt;() println(filteredIsInstanceList) Filter with Set Similar to List, filter operator can be used over a set to check the predicate on its elements return the filtered set. It can be used with a named parameter or using it.\nval set = setOf(1, 2, 3, 4, 5) val filterSet = set.filter { it % 2 == 0 } println(filterSet) val filterSet2 = set.filter { item -\u0026gt; item % 2 == 0 } println(filterSet2) val filterNotSet = set.filterNot { item -\u0026gt; item % 2 == 0 } println(filterNotSet) In the case of filterIndexed, since we have two variables passed in the lambda function, we can not skip the named parameters.\nval set = setOf(1, 2, 3, 4, 5) val filteredIndexSet = set.filterIndexed {index, item -\u0026gt; (index != 0) \u0026amp;\u0026amp; (item % 2 == 0) } println(filteredIndexSet) In the case of filterNotNull, it filter outs the null values and return the set of only the non-null values.\nval set = setOf(1, null, 3, 4, 5, null) val filteredNotNullSet = set.filterNotNull() println(filteredNotNullSet) In the case of filterIsInstance, it filter outs and return the set of the elements of particular data type specified.\nval set = setOf(1, \u0026#34;\u0026#34;, true, 4, 0.0, 0.0f) val filteredIsInstanceSet = set.filterIsInstance\u0026lt;Int\u0026gt;() println(filteredIsInstanceSet) Filter with Map filter operator can be used with map collection similar to the list and set using below functions and named parameters. There are no filterIndexed, filterNotNull and filterIsInstance functions in case of map collection.\nval map = mapOf(\u0026#34;key1\u0026#34; to 1, \u0026#34;key2\u0026#34; to 2, \u0026#34;key3\u0026#34; to 3) val filteredMap = map.filter { entity -\u0026gt; entity.key.contains(\u0026#34;key\u0026#34;) \u0026amp;\u0026amp; entity.value % 2 == 0 } println(filteredMap) val filteredNotMap = map.filterNot { entity -\u0026gt; !entity.key.contains(\u0026#34;key\u0026#34;) || entity.value % 2 != 0 } println(filteredNotMap) In the case of a filter operator with a map collection, we can also filter all keys or values of the map collection and return the filtered map entites which confirm the predicate.\nPlease not that the return type of the filterKeys and filterValues will still be a map.\nval map = mapOf(\u0026#34;key1\u0026#34; to 1, \u0026#34;key2\u0026#34; to 2, \u0026#34;key3\u0026#34; to 3) println(map.filterKeys { key -\u0026gt; key.contains(\u0026#34;key\u0026#34;) }) println(map.filterValues { value -\u0026gt; value % 2 == 0 }) ","tags":["Kotlin"],"title":"Filter Operator : Kotlin"},{"categories":["Blog"],"date":"April 23, 2022","permalink":"https://agrawalsuneet.github.io/blogs/map-operator-kotlin/","section":"blogs","summary":"The collection is something which is used by almost everyone. It makes our life easy. List, Set and Map are the best examples of them.\nTo iterate, filter or modify the existing collection object, Kotlin provides us with a few in builds transform operators. Map operator is one of them.\nLets try to understand the map operator in detail.\nWhat is map operator? Map operator is used to create a new collection object by iterating over the existing collection object and applying some transformation to it. The transformation that needs to be applied is passed as lambda to the function.\nSince the map operator is an extension of the Iterable Interface, it can be used with all three collections ie List, Set and Map.\n/** * Returns a list containing the results of applying the given [transform] function * to each element in the original collection. * * @sample samples.collections.Collections.Transformations.map */ public inline fun \u0026lt;T, R\u0026gt; Iterable\u0026lt;T\u0026gt;.map(transform: (T) -\u0026gt; R): List\u0026lt;R\u0026gt; { return mapTo(ArrayList\u0026lt;R\u0026gt;(collectionSizeOrDefault(10)), transform) } Map also has other few functions as below,\nmapNotNull used for iteration and apply a transform to it but only to the non-null values. This will skip all null values in the list.\nmapIndexed used for indexed iteration and apply a transform to it.\nmapIndexedNotNull used for indexed iteration and apply a transform to it but only to the non-null values. This will skip all null values in the list.\n/** * Returns a list containing only the non-null results of applying the given [transform] function * to each element in the original collection. * * @sample samples.collections.Collections.Transformations.mapNotNull */ public inline fun \u0026lt;T, R : Any\u0026gt; Iterable\u0026lt;T\u0026gt;.mapNotNull(transform: (T) -\u0026gt; R?): List\u0026lt;R\u0026gt; { return mapNotNullTo(ArrayList\u0026lt;R\u0026gt;(), transform) } /** * Returns a list containing the results of applying the given [transform] function * to each element and its index in the original collection. * @param [transform] function that takes the index of an element and the element itself * and returns the result of the transform applied to the element. */ public inline fun \u0026lt;T, R\u0026gt; Iterable\u0026lt;T\u0026gt;.mapIndexed(transform: (index: Int, T) -\u0026gt; R): List\u0026lt;R\u0026gt; { return mapIndexedTo(ArrayList\u0026lt;R\u0026gt;(collectionSizeOrDefault(10)), transform) } /** * Returns a list containing only the non-null results of applying the given [transform] function * to each element and its index in the original collection. * @param [transform] function that takes the index of an element and the element itself * and returns the result of the transform applied to the element. */ public inline fun \u0026lt;T, R : Any\u0026gt; Iterable\u0026lt;T\u0026gt;.mapIndexedNotNull(transform: (index: Int, T) -\u0026gt; R?): List\u0026lt;R\u0026gt; { return mapIndexedNotNullTo(ArrayList\u0026lt;R\u0026gt;(), transform) } Map with List map operator can be used over a list to transform its elements and return the resultant list. It can be used with a named parameter or using it.\nval list = listOf(1, 2, 3, 4, 5) val mapList = list.map{item -\u0026gt; item * 10} println(mapList) val mapList2 = list.map{ it * 10 } println(mapList2) val mapNotNullList = list.mapNotNull{ if (it % 2 == 0) null else it } println(mapNotNullList) map can also be used to transform a list of one data type to a list of another data type. In the below example, List of Int is converted to List of String.\nval list = listOf(1 , 2, 3, 4, 5) val stringList = list.map{ it.toString()} println(stringList::class.simpleName) //this will print: ArrayList println(stringList[0]::class.simpleName) //this will print: String In the case of mapIndexed and mapIndexedNotNull, since we have two variables passed in the lambda function, we can not skip the named parameters.\nval list = listOf(1, 2, 3, 4, 5) val mapIndexedList = list.mapIndexed{index, item -\u0026gt; index * item } println(mapIndexedList) val mapIndexedNotNullList = list.mapIndexedNotNull{ index, item -\u0026gt; if (it % 2 == 0) null else (item * index) } println(mapIndexedNotNullList) Map with Set Similar to List, map operator can be used over a set to transform its elements and return the resultant set. It can be used with a named parameter or using it.\nval set = setOf(1, 2, 3, 4, 5) val mapSet = set.map{item -\u0026gt; item * 10} println(mapSet) val mapSet2 = set.map{ it * 10 } println(mapSet2) val mapSetNotNull = list.mapNotNull{ if (it % 2 == 0) null else it } println(mapSetNotNull) map can also be used to transform a set of one data type to a list of another data type. In the below example, Set of Int is converted to Set of String.\nval set = setOf(1, 2, 3, 4, 5) val stringSet = set.map{ it.toString()} println(stringSet::class.simpleName) //this will print: ArrayList println(stringSet[0]::class.simpleName) //this will print: String In the case of mapIndexed and mapIndexedNotNull, since we have two variables passed in the lambda function, we can not skip the named parameters.\nval set = setOf(1, 2, 3, 4, 5) val mapIndexedSet = set.mapIndexed{index, item -\u0026gt; index * item } println(mapIndexedSet) val mapIndexedNotNullSet = set.mapIndexedNotNull{ index, item -\u0026gt; if (it % 2 == 0) null else (item * index) } println(mapIndexedNotNullSet) Map with Map map operator can be used with map collection similar to the list and set using below functions and named parameters. There are no mapIndexed and mapIndexedNotNull functions in case of map collection.\nval numbersMap = mapOf(\u0026#34;key1\u0026#34; to 1, \u0026#34;key2\u0026#34; to 2, \u0026#34;key3\u0026#34; to 3) println(numbersMap.map { entry -\u0026gt; entry.key to (entry.value * 10) }) println(numbersMap.mapNotNull { it }) In the case of using a map operator with a map collection, we can also iterate over all keys or values of the map collection and apply the transformation to it.\nval numbersMap = mapOf(\u0026#34;key1\u0026#34; to 1, \u0026#34;key2\u0026#34; to 2, \u0026#34;key3\u0026#34; to 3) println(numbersMap.mapKeys { it.key.uppercase() }) println(numbersMap.mapValues { it.value + it.key.length }) ","tags":["Kotlin"],"title":"Map Operator : Kotlin"},{"categories":["Blog"],"date":"April 11, 2022","permalink":"https://agrawalsuneet.github.io/blogs/math-round-vs-math-floor-vs-math-ceil-kotlin/","section":"blogs","summary":"Rounding up to the nearest Integer value functionality is something required a lot of times. Kotlin has a few inbuilt functions which can do the rounding up for us but they are a bit confusing. To decide when to use what, we need to understand which rounding function rounds up in which direction and which data types it can round up.\nLet\u0026rsquo;s understand them in detail before comparing.\nBefore reading this blog, keep in mind that -3 is bigger than -4 and -3.5 is bigger than -3.51\nMath.round() Math.round rounds up to the nearest Integer which can be above or below or even equal to the actual value. In the case of a positive number, anything which is equal to or below x.49 will be converted to a lower number ie x.00 whereas anything which is equal to or more than x.5 will be converted to a higher number ie x+1.00 In the case of a negative number, anything which is equal to or below -x.51 will be converted to a lower number ie -x-1.00 whereas anything which is equal to or more than -x.5 will be converted to a higher number ie -x.00 println(Math.round(3.00)) //this will print: 3 println(Math.round(3.49)) //this will print: 3 println(Math.round(3.5)) //this will print: 4 println(Math.round(-3.00)) //this will print: -3 println(Math.round(-3.5)) //this will print: -3 println(Math.round(-3.51)) //this will print: -4 Math.floor() Math.floor rounds up to the nearest Integer which can be equal to or below the actual value. In the case of a positive number, anything between x.01 to x.99 will be converted to a lower number ie x.00 whereas x.00 will remain the same x.00 In the case of a negative number, anything between -x.01 to -x.99 will be converted to a lower number ie -x-1.00 whereas -x.00 will remain the same -x.00 println(Math.floor(3.00)) //this will print: 3 println(Math.floor(3.01)) //this will print: 3 println(Math.floor(3.99)) //this will print: 3 println(Math.floor(-3.00)) //this will print: -3 println(Math.floor(-3.01)) //this will print: -4 println(Math.floor(-3.99)) //this will print: -4 Math.ceil() Math.ceil rounds up to the nearest Integer which can be equal to or above the actual value. In the case of a positive number, anything between x.01 to x.99 will be converted to an upper number ie x+1.00 whereas x.00 will remain the same x.00 In the case of a negative number, anything between -x.01 to -x.99 will be converted to an upper number ie -x.00 whereas -x.00 will remain the same -x.00 println(Math.ceil(3.00)) //this will print: 3 println(Math.ceil(3.01)) //this will print: 4 println(Math.ceil(3.99)) //this will print: 4 println(Math.ceil(-3.00)) //this will print: -3 println(Math.ceil(-3.01)) //this will print: -3 println(Math.ceil(-3.99)) //this will print: -3 Common between Math.round, Math.floor and Math.ceil All three work on both Double as well as on Float. Although they round to the nearest Integer, the output still remains Double in the case of Double and Float in the case of Float. Difference between Math.round, Math.floor and Math.ceil Math.round rounds up to the nearest Integer which can be above, below or equal to the actual value.\nx.0 to x.49 -\u0026gt; x.0 x.5 to x.99 -\u0026gt; x+1.0 -x to -x.5 -\u0026gt; x.0 -x.51 to -x.99 -\u0026gt; -x-1.0 Math.floor rounds up to the nearest Integer which can be equal to or below the actual value.\nx.0 to x.99 -\u0026gt; x.0 -x.01 to -x.99 -\u0026gt; -x-1.0 Math.ceil rounds up to the nearest Integer which can be equal to or above the actual value.\nx.01 to x.99 -\u0026gt; x+1.0 -x.01 to -x.99 -\u0026gt; -x.0 The third digit after decimal doesn\u0026rsquo;t make any difference. ","tags":["Kotlin"],"title":"Math.round vs Math.floor vs Math.ceil : Kotlin"},{"categories":["Blog"],"date":"April 10, 2022","permalink":"https://agrawalsuneet.github.io/blogs/double-vs-float-swift/","section":"blogs","summary":"Swift has two data types (Double and Float) to hold the decimal values. Both of them hold the same decimal type values but have some differences.\nThe basic difference is around the size of memory they both use based on which their precision varies.\nLet\u0026rsquo;s try to understand the differences between both with example.\nNumber of Digits The Double type is used to store values in up to 17 places. It starts from the leftmost side and reduces the digits from the right side of the value if exceeding 17 places. The Float type is used to store values in up to 8 places. It also starts from the leftmost side and reduces the digits from the right side of the value if exceeding 8 places. var doubleVariable : Double = 1234567890.1234567890 var floatVariable : Float = 12345.12345 print(doubleVariable) //this will print only 17 digits from left //1234567890.1234567 print(floatVariable) //this will print only 8 digits from left //12345.123 Memory Size Double takes 8 bytes of memory. Float takes only 4 bytes of memory var doubleVariable : Double = 1234567890.1234567890 var floatVariable : Float = 12345.12345 print(MemoryLayout.size(ofValue: doubleVariable)) //this will print //8 (bytes) print(MemoryLayout.size(ofValue: floatVariable)) //this will print //4 (bytes) Default Type If we don\u0026rsquo;t define any type and directly assign the value, the compiler initialises it as Double. var defaultVariable = 1.00 var doubleVariable : Double = 1234567890.1234567890 var floatVariable : Float = 12345.12345 print(type(of: defaultVariable)) //this will print //Double print(type(of: doubleVariable)) //this will print //Double print(type(of: floatVariable)) //this will print //Float Conclusion The Double is more precise than the Float as it has more decimal digits. The Double takes more memory than the Float. If there no data type is defined explicitly and if we assign any decimal value to a variable, the compiler treats it as Double. When to Use What For places where no extra precision is required, use Float. Like amount where up to 2 decimal digits can work. If confused about what to use and not sure where the value can go, use Double. ","tags":["Swift"],"title":"Double vs Float : Swift"},{"categories":["Blog"],"date":"April 10, 2022","permalink":"https://agrawalsuneet.github.io/blogs/for-in-vs-for-each-in-swift/","section":"blogs","summary":"For-in and for-each are different variants of for loops in swift which are used to iterate over a range, set or dictionary. Both provide the same functionality but has a few limitations or differences when it comes to conditional access.\nTo understand their differences, let\u0026rsquo;s try to understand their examples in details first.\nFor-in loop For-in loop is used to iterate over a range, set or dictionary using both the indexes as well an element based iteration.\nfor item in 0...5 { print(item) } let dictionary = [\u0026#34;Suneet\u0026#34;: \u0026#34;Engineering\u0026#34;, \u0026#34;Ballu\u0026#34;: \u0026#34;Sales\u0026#34;, \u0026#34;John\u0026#34;: \u0026#34;Marketing\u0026#34;] for (name, department) in dictionary { print(\u0026#34;\\(name) is working in \\(department) department\u0026#34;) } let set = [\u0026#34;Suneet\u0026#34;, \u0026#34;Agrawal\u0026#34;, \u0026#34;Ballu\u0026#34;] for item in set { print(item) } For-each loop For-each loop can also be used to iterate over a range, set or dictionary using both the indexes as well an element based iteration.\n(0...5).forEach{ item in print(item) } let dictionary = [\u0026#34;Suneet\u0026#34;: \u0026#34;Engineering\u0026#34;, \u0026#34;Ballu\u0026#34;: \u0026#34;Sales\u0026#34;, \u0026#34;John\u0026#34;: \u0026#34;Marketing\u0026#34;] dictionary.forEach{ name, department in print(\u0026#34;\\(name) is working in \\(department) department\u0026#34;) } let set = [\u0026#34;Suneet\u0026#34;, \u0026#34;Agrawal\u0026#34;, \u0026#34;Ballu\u0026#34;] set.forEach{ item in print(item) } Difference between for-in and for-each 1. Break and continue statements cannot be used in for-each loop break and continue are the basic syntaxes of for loop which is used to either break the loop iteration or to continue to the next element.\nSince for-each is not an operator but it\u0026rsquo;s a function, break and continue can\u0026rsquo;t be used inside a for-each iteration.\n//For-in loop var evenNumbers = [Int]() for number in 0...50 { guard evenNumbers.count \u0026lt; 5 else { break } guard number % 2 == 0 else { continue } evenNumbers.append(number) } print(evenNumbers) //this will print [0, 2, 4, 6, 8] ------------------------------------------- //For-each loop var evenNumbers = [Int]() (0...50).forEach{ number in guard evenNumbers.count \u0026lt; 5 else { break //Error: \u0026#39;break\u0026#39; is only allowed inside a loop, if, do, or switch } guard number % 2 == 0 else { continue //\u0026lt;e\u0026gt;\u0026#39;continue\u0026#39; is only allowed inside a loop } evenNumbers.append(number) } print(evenNumbers) 2. Return from scope is not possible from for-in loop Return from the scope of the for loop is not possible in the case of the for-in loop. Please note that we can use return in the for-in loop if inside a function, but that will return from the function but not from the for-loop scope.\n//For-in loop var evenNumbers = [Int]() for number in 0...50 { guard evenNumbers.count \u0026lt; 5 else { return //\u0026lt;e\u0026gt;Return invalid outside of a func } guard number % 2 == 0 else { return //\u0026lt;e\u0026gt;Return invalid outside of a func } evenNumbers.append(number) } print(evenNumbers) ------------------------------------------- //For-each loop var evenNumbers = [Int]() (0...50).forEach{ number in guard evenNumbers.count \u0026lt; 5 else { return } guard number % 2 == 0 else { return } evenNumbers.append(number) } print(evenNumbers) //this will print [0, 2, 4, 6, 8] 3. For-each can be used with Swift\u0026rsquo;s closures or first class functions Since for-each is a function but not an operator, it can be used with closures or first-class functions whereas the same is not possible with the case of the for-in loop. //For-each loop func doSomethingWithNumber(for number : Int){ guard number % 2 == 0 else { return } print(number) } (0...10).forEach(doSomethingWithNumber) To sum it up For-in is an operator whereas for-each is a function. For-in loop gives us a much greater degree of control over an iteration like using break, continue. For-each enables us to take advantage of the power of closures and first-class functions. ","tags":["Swift"],"title":"For-in vs For-each in Swift"},{"categories":["Blog"],"date":"April 9, 2022","permalink":"https://agrawalsuneet.github.io/blogs/custom-object-in-userdefaults-swift/","section":"blogs","summary":"In continuation to my previous blog UserDefaults in Swift, where we understand the basic functionality of UserDefaults, we\u0026rsquo;ll try to understand today how can we store custom objects in UserDefaults.\nUserDefaults provides us with direct functions for storing primitive data types like Int, Double, Bool, and String. But for custom data types, there is no direct way to store them in UserDefaults. But there is a workaround with which we can store the custom object to UserDefaults. Let\u0026rsquo;s try to understand in detail along with an example.\nWhat are Custom Objects and Codable? User-defined class or struct objects are known as custom objects. These classes or structs can have any number of properties.\nTo store them in UserDefaults, we need to implement or confirm `Codable to the user-defined class or struct.\nCodable is a typealias of Decodable \u0026amp; `Encodable protocols. It adds the functionality of Encoding and Decoding to the class or struct.\n/// A type that can convert itself into and out of an external representation. /// /// `Codable` is a type alias for the `Encodable` and `Decodable` protocols. /// When you use `Codable` as a type or a generic constraint, it matches /// any type that conforms to both protocols. public typealias Codable\u0026lt;/b\u0026gt; = Decodable\u0026lt;/b\u0026gt; \u0026amp; Encodable\u0026lt;/b\u0026gt; To implement or confirm the `Codable protocol, we can add the protocol and go with coding keys as the variable names or can define our own custom keys according to the need.\n//MARK :- Employee struct Employee\u0026lt;/b\u0026gt;: Codable\u0026lt;/b\u0026gt; { let employeeId: Int let name, department: String } // OR //MARK :- Employee struct Employee\u0026lt;/b\u0026gt;: Codable\u0026lt;/b\u0026gt; { let employeeID: Int let name, department: String enum CodingKeys: String, CodingKey { case employeeID = \u0026#34;employeeId\u0026#34; case name, department } } Keep in mind that any custom class used inside the Codable class or struct should also confirm the Codable protocol.\nHow to store custom object in UserDefaults? Codable provides the functionality to convert an object into a Data class object.\nUserDefaults has a function similar to primitive data types which takes an `Any? class object and store the value against the key provided.\n/** -setObject:forKey: immediately stores a value (or removes the value if nil is passed as the value) for the provided key in the search list entry for the receiver\u0026#39;s suite name in the current user and any host, then asynchronously stores the value persistently, where it is made available to other processes. */ open func set\u0026lt;/b\u0026gt;(_ value: Any?, forKey defaultName: String) We can\u0026rsquo;t provide the object directly but we need to convert the object into a Data class object using JSONEncoder, else it will throw the below error.\n\u0026lt;e\u0026gt;Attempt to insert non-property list object \u0026lt;object name\u0026gt; for key \u0026lt;key\u0026gt;\u0026lt;/e\u0026gt; Also, since JSONEncoder can throw an error if the object is not encoded properly, we need to wrap it around the try-catch block.\nOnce the codable is converted to the Data class object, we can put it into UserDefaults using the above set method.\nThe final code will look like the below.\nlet employee = Employee(employeeId: 100, name: \u0026#34;Suneet Agrawal\u0026#34;, department: \u0026#34;Engineering\u0026#34;) do { let data = try JSONEncoder()\u0026lt;/b\u0026gt;.encode(employee) UserDefaults.standard.set\u0026lt;/b\u0026gt;(data, forKey: \u0026#34;employee\u0026#34;) } catch let error { print(\u0026#34;Error encoding: \\(error)\u0026#34;) } How to retrieve custom object from UserDefaults? UserDefaults has a function to retrieve `Data class objects similar to any other primitive data type.\nThe same can be used to retrieve data from UserDefaults but the returned result will be in the `Data? class object.\n/// -dataForKey: is equivalent to -objectForKey:, except that it will return nil if the value is not an NSData. open func data(forKey defaultName: String) -\u0026gt; Data? Keep in mind that it can also return nil if no such data is stored with the key. In that case, we need to add a null safety also.\nif let data = UserDefaults.standard.data(\u0026lt;/b\u0026gt;forKey: \u0026#34;employee\u0026#34;) { //do something here } Now that we got the data back, we can convert it into the same original class or struct object (Employee in our case) using JSONDecoder.\nBut similar to JSONEncoder, JSONDecoder can also throw an error if the object is not decoded properly, we need to wrap it around the `try-catch block.\ndo { if let data = UserDefaults.standard.data\u0026lt;/b\u0026gt;(forKey: \u0026#34;employee\u0026#34;) { let employee = try JSONDecoder\u0026lt;/b\u0026gt;().decode(Employee.self, from: data) print(employee) } } catch let error { print(\u0026#34;Error decoding: \\(error)\u0026#34;) } Generic Extension We can even add a generic functionality to the UserDefaults class which will store the `Codable class or struct object of Template type and retrieve back the same object using the same key.\nThe above functions can be used as below.\nlet employee = Employee(employeeId: 100, name: \u0026#34;Suneet\u0026#34;, department: \u0026#34;Engineering\u0026#34;) //setting the object UserDefaults.standard.storeCodable\u0026lt;/b\u0026gt;(employee, key: \u0026#34;employee\u0026#34;) //getting the object let emp : Employee? = UserDefaults.standard.retrieveCodable\u0026lt;/b\u0026gt;(for: \u0026#34;employee\u0026#34;) print(emp) //this will print optional if let emp = emp { print(emp) } ","tags":["Swift"],"title":"Custom Object in UserDefaults : Swift"},{"categories":["Gist"],"date":"April 9, 2022","permalink":"https://agrawalsuneet.github.io/gists/custom-object-in-userdefaults-swift/","section":"gists","summary":"This particular script will help you to store and retrieve custom class or struct objects in UserDefaults.\nFor further explaination on how this works, please read the article Custom Object in UserDefaults : Swift.\n","tags":["Swift"],"title":"Custom Object in UserDefaults : Swift"},{"categories":["Blog"],"date":"March 24, 2022","permalink":"https://agrawalsuneet.github.io/blogs/userdefaults-in-swift/","section":"blogs","summary":"A small set of data is required to be stored and accessed very frequently and need to be persisted across sessions or app launches. One way of keeping them is using a local database like core data in an iOS app. But core data is helpful in the case of tables and queries. There is another way to store a small set of data, UserDefaults.\nLet\u0026rsquo;s try to understand what are UserDefaults first.\nWhat is UserDefaults UserDefault is used to store small pieces of data which can persist across sessions or app launches. Things like auth token, username, emailid, display name which are being used accross the sessions can be store in UserDefaults.\nHow UserDefaults works UserDefaults stores data in a key-value pair where the key can be of string type and value can be of Int, Float, Double, Bool, String, Data, URL, Array, Dictionary and much more.\nThe information will be stored in a .plist format on the local disk.\nCurrently, there is no size limit to store data in UserDefaults but it\u0026rsquo;s usually preferred for the small size of data only.\nHow to use UserDefaults In order to use the UserDefaults, first, get the standard UserDefault object.\nlet defaults = UserDefaults.standard standard is a global instance of NSUserDefaults or which only getter is exposed. We can\u0026rsquo;t set any reference to it.\n/** +standardUserDefaults returns a global instance of NSUserDefaults configured to search the current application\u0026#39;s search list. */ open class var standard: UserDefaults { get } Write data to UserDefaults We can set the value for any key using set function on UserDefault.standard object. The set method has multiple overloads that have the same signature but takes different parameters as a value along with a String key.\nlet defaults = UserDefaults.standard //String Value defaults.set(\u0026#34;Suneet Agrawal\u0026#34;, forKey: \u0026#34;stringKey\u0026#34;) //Int Value defaults.set(1, forKey: \u0026#34;integerKey\u0026#34;) //Double Value defaults.set(30.0, forKey: \u0026#34;doubleKey\u0026#34;) //Array Value defaults.set([1,2,3], forKey: \u0026#34;intArrayKey\u0026#34;) Read data from UserDefaults The syntax for getting the value from UserDefault is a bit different from set. Each has the datatype as a function name which takes a key as a String type parameter for which we want to get the value.\nKeep in mind these function returns nil if there is no value existing for the key or is of a different datatype.\nlet defaults = UserDefaults.standard //String Value let stringValue = defaults.string(forKey: \u0026#34;stringKey\u0026#34;) //Int Value let intValue = defaults.integer(forKey: \u0026#34;integerKey\u0026#34;) //Double Value let doubleValue = defaults.double(forKey: \u0026#34;doubleKey\u0026#34;) //Array Value let intArrayValue = defaults.string(forKey: \u0026#34;intArrayKey\u0026#34;) Remove data for key The value for a particular key can be removed using removeObject function. This will set the value as nil.\n/// -removeObjectForKey: is equivalent to -[... setObject:nil forKey:defaultName] open func removeObject(forKey defaultName: String) let defaults = UserDefaults.standard defaults.removeObject(forKey: \u0026#34;stringKey\u0026#34;) Remove data for all keys There is no direct function to remove all key-value pairs. The best way to do the same is to iterate over all the keys and remove them one by one.\nfor key in Array(UserDefaults.standard.dictionaryRepresentation().keys) { UserDefaults.standard.removeObject(forKey: key) } Default value for key in UserDefaults The behavior for the get type is weird if the key is not set.\nIn that case, if we are trying to get the value for any primitive data type, it will return a default value like 0 for Integer but if we are trying to get an object value, it will return nil.\nIn order to unify the behavior across the app, we can use object(forKey:) function which returns Any? and we can cast it to the required datatype. We can even provide the default value if it returns nil or the key doesn\u0026rsquo;t exist.\nlet defaultValue = UserDefaults.standard.object(forKey: \u0026#34;intArrayKey\u0026#34;) as? [Int]? ?? [Int]() Things to keep in mind while using UserDefault It stores data in key-value pairs. The key-value pairs are stored in .plist format on the local disk. We can store multiple data types in UserDefault. UserDefault is useful only for a small set of data. It is not a replacement for core data. ","tags":["Swift"],"title":"UserDefaults in Swift"},{"categories":["Blog"],"date":"March 20, 2022","permalink":"https://agrawalsuneet.github.io/blogs/uiswitch-value-change-listener-swift/","section":"blogs","summary":"Adding an value change event to a UISwitch is something that is required most of the time. For views like UISwitch, we can connect an IBAction with the event type as value changed and get a callback for the value changed.\nIf you are not using xib or storyboard but creating the layout programmatically or by using swiftUI, you can the editing event using a target action that takes three parameters,\ntarget of Any type which is nullable action of Selector type controlEvents of UIControl.Event The code for the same will look like below.\n//swift code in viewcontroller self.switch.addTarget(self, action: #selector(onSwitchValueChanged(_:)), for: .valueChanged) @objc private func onSwitchValueChanged(_ switch: UISwitch) { //do something here } Since the Selector takes only @objc functions which can only be defined as a member of the class or an extension of the class, we need to define it at a class level only.\n//error @objc can only be used with members of classes, @objc protocols, and concrete extensions of classes This way is a bit inefficient as we need to add one function for each UISwitch where we need editing event.\nThere is a better way where we can add this functionality to each UISwitch without making our class messy.\nWe can add this to the UISwitch extension itself which will be a very clean approach and will make our life super easy.\nFirst, add a function as an extension to UISwitch class which takes a function as a parameter with 0 params and Void return type.\nSince this function will be our callback function, add @escaping to the function passed as the parameter.\n//MARK: - UISwitch Extension extension UISwitch { func setOnValueChangeListener(onValueChanged :@escaping () -\u0026gt; Void){ } } Now add an action to the UISwitch object in the same function which takes two parameters.\naction of UIAction type controlEvents of UIControl.Event There are multiple constructors for UIAction but will take the most simple one where it takes one parameter ie handler of UIActionHandler type. Rest all params either have a default value or are of nullable types.\nAnd, we can call our callback function in the handler callback.\n//MARK: - UISwitch Extension @available(iOS 14.0, *) extension UISwitch { func setOnValueChangeListener(onValueChanged :@escaping () -\u0026gt; Void){ self.addAction(UIAction(){ action in onValueChanged() }, for: .valueChanged) } } This took care of all the boilerplate code and added a simple public function to each UISwitch for text change event.\nTo call this function, simply call setOnValueChangeListener to any UISwitch in your ViewController.\n//swift code in view viewcontroller self.switch.setOnValueChangeListener { print(\u0026#34;value changed\u0026#34;) } No extra function required in ViewController and it will be very clean.\nBut keep in mind, the function addAction is only available in iOS 14 or above If your codebase still supports below iOS 14, then you need to go with the addTarget and Selector function only.\nComplete code ","tags":["Swift"],"title":"UISwitch Value Change Listener : Swift"},{"categories":["Gist"],"date":"March 20, 2022","permalink":"https://agrawalsuneet.github.io/gists/uiswitch-value-change-listener-swift/","section":"gists","summary":"This particular script will help you to implement a Value Change listener to all UISwitch and its subclasses in a clean way.\nFor further explaination on how this works, please read the article[UISwitch Value Change Listener : Swift] (/blogs/uiswitch-value-change-listener-swift/).\n","tags":["Swift"],"title":"UISwitch Value Change Listener : Swift"},{"categories":["Blog"],"date":"March 9, 2022","permalink":"https://agrawalsuneet.github.io/blogs/uidatepicker-date-change-listener-swift/","section":"blogs","summary":"Adding an editing event to a UIDatePicker is something that is required most of the time. For views like UIDatePicker, we can connect an IBAction with the event type as value changed and get a callback for the value changed.\nIf you are not using xib or storyboard but creating the layout programmatically or by using swiftUI, you can the editing event using a target action that takes three parameters,\ntarget of Any type which is nullable action of Selector type controlEvents of UIControl.Event The code for the same will look like below.\n//swift code in viewcontroller self.datePicker.addTarget(self, action: #selector(onDateValueChanged(_:)), for: .valueChanged) @objc private func onDateValueChanged(_ datePicker: UIDatePicker) { //do something here } Since the Selector takes only @objc functions which can only be defined as a member of the class or an extension of the class, we need to define it at a class level only.\n//error @objc can only be used with members of classes, @objc protocols, and concrete extensions of classes This way is a bit inefficient as we need to add one function for each UIDatePicker where we need editing event.\nThere is a better way where we can add this functionality to each UIDatePicker without making our class messy.\nWe can add this to the UIDatePicker extension itself which will be a very clean approach and will make our life super easy.\nFirst, add a function as an extension to UIDatePicker class which takes a function as a parameter with 0 params and Void return type.\nSince this function will be our callback function, add @escaping to the function passed as the parameter.\n//MARK: - UIDatePicker Extension extension UIDatePicker { func setOnDateChangeListener(onDateChanged :@escaping () -\u0026gt; Void){ } } Now add an action to the UIDatePicker object in the same function which takes two parameters.\naction of UIAction type controlEvents of UIControl.Event There are multiple constructors for UIAction but will take the most simple one where it takes one parameter ie handler of UIActionHandler type. Rest all params either have a default value or are of nullable types.\nAnd, we can call our callback function in the handler callback.\n//MARK: - UIDatePicker Extension @available(iOS 14.0, *) extension UIDatePicker { func setOnDateChangeListener(onDateChanged :@escaping () -\u0026gt; Void){ self.addAction(UIAction(){ action in onDateChanged() }, for: .valueChanged) } } This took care of all the boilerplate code and added a simple public function to each UIDatePicker for text change event.\nTo call this function, simply call setOnDateChangeListener to any UIDatePicker in your ViewController.\n//swift code in view viewcontroller self.datePicker.setOnDateChangeListener { print(\u0026#34;date changed\u0026#34;) } No extra function required in ViewController and it will be very clean.\nBut keep in mind, the function addAction is only available in iOS 14 or above If your codebase still supports below iOS 14, then you need to go with the addTarget and Selector function only.\nComplete code ","tags":["Swift"],"title":"UIDatePicker Date Change Listener : Swift"},{"categories":["Gist"],"date":"March 9, 2022","permalink":"https://agrawalsuneet.github.io/gists/uidatepicker-date-change-listener-swift/","section":"gists","summary":"This particular script will help you to implement a Date Change listener to all UIDatePicker and its subclasses in a clean way.\nFor further explaination on how this works, please read the article UIDatePicker Date Change Listener: Swift.\n","tags":["Swift"],"title":"UIDatePicker Date Change Listener : Swift"},{"categories":["Blog"],"date":"March 8, 2022","permalink":"https://agrawalsuneet.github.io/blogs/uitextfield-text-listener-swift/","section":"blogs","summary":"Adding an editing event to a UITextField is something that is required most of the time. For views like UITextField, we can connect an IBAction with the event type as editing did end or value changed and get a callback for editing finished or value changed.\nIf you are not using xib or storyboard but creating the layout programmatically or by using swiftUI, you can the editing event using a target action that takes three parameters,\ntarget of Any type which is nullable action of Selector type controlEvents of UIControl.Event The code for the same will look like below.\n//swift code in viewcontroller self.inputTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) @objc private func textFieldDidChange(_ textField: UITextField) { //do something here } Since the Selector takes only @objc functions which can only be defined as a member of the class or an extension of the class, we need to define it at a class level only.\n//error @objc can only be used with members of classes, @objc protocols, and concrete extensions of classes This way is a bit inefficient as we need to add one function for each UITextField where we need editing event.\nThere is a better way where we can add this functionality to each UITextField without making our class messy.\nWe can add this to the UITextField extension itself which will be a very clean approach and will make our life super easy.\nFirst, add a function as an extension to UITextField class which takes a function as a parameter with 0 params and Void return type.\nSince this function will be our callback function, add @escaping to the function passed as the parameter.\n//MARK: - UITextField Extension extension UITextField { func setOnTextChangeListener(onTextChanged :@escaping () -\u0026gt; Void){ } } Now add an action to the UITextField object in the same function which takes two parameters.\naction of UIAction type controlEvents of UIControl.Event There are multiple constructors for UIAction but will take the most simple one where it takes one parameter ie handler of UIActionHandler type. Rest all params either have a default value or are of nullable types.\nAnd, we can call our callback function in the handler callback.\n//MARK: - UITextField Extension @available(iOS 14.0, *) extension UITextField { func setOnTextChangeListener(onTextChanged :@escaping () -\u0026gt; Void){ self.addAction(UIAction(){ action in onTextChanged() }, for: .editingChanged) } } This took care of all the boilerplate code and added a simple public function to each UITextField for text change event.\nTo call this function, simply call setOnTextChangeListener to any UITextField in your ViewController.\n//swift code in viewcontroller self.inputTextField.setOnTextChangeListener { print(\u0026#34;text changed\u0026#34;) } No extra function required in ViewController and it will be very clean.\nBut keep in mind, the function addAction is only available in iOS 14 or above If your codebase still supports below iOS 14, then you need to go with the addTarget and Selector function only.\nComplete code ","tags":["Swift"],"title":"UITextField Text Listener : Swift"},{"categories":["Gist"],"date":"March 8, 2022","permalink":"https://agrawalsuneet.github.io/gists/uitextfield-text-listener-swift/","section":"gists","summary":"This particular script will help you to implement a Text listener to all UITextField and its subclasses in a clean way.\nFor further explaination on how this works, please read the article UITextField TextListener : Swift.\n","tags":["Swift"],"title":"UITextField Text Listener : Swift"},{"categories":["Blog"],"date":"February 27, 2022","permalink":"https://agrawalsuneet.github.io/blogs/switch-statement-in-swift/","section":"blogs","summary":"The switch statement in Swift is used to execute a particular block of code based on multiple conditions. A switch statement is useful for more than one condition. For one or two conditions, if-else is a better option but for conditions more than that, a switch statement is a better option.\nWe will try to understand the flow of switch statement in detail but let\u0026rsquo;s try to understand its basic syntax first.\nThe switch statement begins with a switch keyword followed by an expression based on which the cases will be evaluated.\nThe expression is followed by different cases and the code block for each case.\nIf none of the cases matches, the default block will be executed.\nThe basic syntax will look like below.\nswitch (expression) { case value1: // statements case value2: // statements ... ... default: // statements } Let\u0026rsquo;s try to understand it with a flow chart before taking an example.\nThe below flow chart explains the basic flow of a switch statement which starts with an expression followed by cases. If the condition matches, the code block for that case will be executed. If non of the cases match, the default case will be executed.\nNow let\u0026rsquo;s see an example for the switch statement.\nlet dayOfWeek = 2 switch dayOfWeek {\tcase 1: print(\u0026#34;Monday\u0026#34;) case 2: print(\u0026#34;Tuesday\u0026#34;) case 3: print(\u0026#34;Wednesday\u0026#34;) case 4: print(\u0026#34;Thursday\u0026#34;) case 5: print(\u0026#34;Friday\u0026#34;) case 6: print(\u0026#34;Saturday\u0026#34;) case 7: print(\u0026#34;Sunday\u0026#34;) default: print(\u0026#34;Invalid day\u0026#34;) } //this will print //Monday Things to notice here Like other languages, there is no need for a break statement in the cases. There is no limit on the number of cases. No case can be empty, at least one line of executable code should be there otherwise the compiler will throw the below error. error: case label in a switch should have at least one executable statement The default case is a must until the switch case is on an enum and/or all cases are exhausted otherwise the compiler will through the below error. error: switch must be exhaustive note: do you want to add a default clause? Switch Statement with fallthrough The fallthrough is being used in the switch cases where we want the compiler to enter into the next case also even if the condition is not true. Usually, for the situation where we want to execute some common code for two switch cases, we can use fallthrough.\nlet dayOfWeek = 6 switch dayOfWeek {\tcase 1: print(\u0026#34;Monday\u0026#34;) case 2: print(\u0026#34;Tuesday\u0026#34;) case 3: print(\u0026#34;Wednesday\u0026#34;) case 4: print(\u0026#34;Thursday\u0026#34;) case 5: print(\u0026#34;Friday\u0026#34;) case 6: fallthrough case 7: print(\u0026#34;Its a holiday\u0026#34;) default: print(\u0026#34;Invalid day\u0026#34;) } //this will print //Its a holiday The fallthrough can also be replaced with comma-separated cases, where the same code block will be executed for both the cases, but in the case of fallthrough, some extra line of code can be added for the above case before moving to the next case code block.\nlet dayOfWeek = 6 switch dayOfWeek {\t... case 6, 7: print(\u0026#34;Its a holiday\u0026#34;) default: print(\u0026#34;Invalid day\u0026#34;) } //this will print //Its a holiday Let\u0026rsquo;s try to understand fallthrough with a flow chart.\nSwitch Statement with Range Operator A switch statement can be clubbed with range operators.\nBelow is the example for the same.\nlet marks = 30 switch marks {\tcase 90...100: print(\u0026#34;Wonderful\u0026#34;) case 70..\u0026lt;90: print(\u0026#34;Very Good\u0026#34;) case 35..\u0026lt;70: print(\u0026#34;Scope of improvement\u0026#34;) case ..\u0026lt;35: print(\u0026#34;Need immediate attention !\u0026#34;) default: print(\u0026#34;Invalid Marks\u0026#34;) } Switch Statement with Tuple A switch statement can be clubbed with Tuple also where both the values need to match in order to execute any case code block.\nBelow is the example for the same.\nlet user = (\u0026#34;Suneet\u0026#34;, 30) switch user { case (\u0026#34;Suneet\u0026#34;, 30): print(\u0026#34;Suneet user found\u0026#34;) case (\u0026#34;Agrawal\u0026#34;, 30): print(\u0026#34;Agrawal user found\u0026#34;) default: print(\u0026#34;Unknown user\u0026#34;) } Please keep in mind, in the case of a tuple, both the values should match for any case to be executed.\n","tags":["Swift"],"title":"Switch Statement in Swift"},{"categories":["Blog"],"date":"January 15, 2022","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-range-operator/","section":"blogs","summary":"Range Operator in Kotlin is a basic operator that is used to operate over a range. A range can be defined with a start value and an end value with and without inclusion.\nThe range operators can be used with for loops, if conditions or even in when operator. First, let to see a basic example of a range operator.\nA basic range operator can be defined with .. having a lower range value to the left side and upper range value to the right side of ..\nval x = 4 for (item in 1..10){ println(item) } if ((1..10).contains(x)){ println(\u0026#34;X is in range\u0026#34;) } when (x){ in 1..10 -\u0026gt; { println(\u0026#34;X is in range\u0026#34;) } } Lets try to understand the .. operator and its return type first.\nrangeTo() function .. is an operator overloading to rangeTo() function which is defined in kotlin.ranges package.\nrangeTo() function is an extension function to the Template class where the Template class should implement the Comparable interface.\nThat means we can create a range to any primitive or non primitive data type which implements the Comparable interface.\n/** * Creates a range from this [Comparable] value to the specified [that] value. * * This value needs to be smaller than or equal to [that] value, otherwise the returned range will be empty. * @sample samples.ranges.Ranges.rangeFromComparable */ public operator fun \u0026amp;lt;T : Comparable\u0026amp;lt;T\u0026amp;gt;\u0026amp;gt; T.rangeTo(that: T): ClosedRange\u0026amp;lt;T\u0026amp;gt; = ComparableRange(this, that) ClosedRange The rangeTo() function returns a ClosedRange interface object which has a start and an endInclusive variables and contains operator function which is used by the in operator and an isEmpty function.\npackage kotlin.ranges /** * Represents a range of values (for example, numbers or characters). */ public interface ClosedRange\u0026amp;lt;T: Comparable\u0026amp;lt;T\u0026amp;gt;\u0026amp;gt; { /** * The minimum value in the range. */ public val start: T /** * The maximum value in the range (inclusive). */ public val endInclusive: T /** * Checks whether the specified [value] belongs to the range. */ public operator fun contains(value: T): Boolean = value \u0026gt;= start \u0026amp;\u0026amp; value \u0026lt;= endInclusive /** * Checks whether the range is empty. * * The range is empty if its start value is greater than the end value. */ public fun isEmpty(): Boolean = start \u0026amp;gt; endInclusive } CharRange, IntRange \u0026amp; LongRange ClosedRange is further extended by CharRange, IntRange and LongRange which provides the functionality of Iterable also along with closed range which is used by [for loops](/blogs/kotlin-for-loop/\u0026quot; target=\u0026quot;_blank\u0026quot;).\npackage kotlin.ranges /** * A range of values of type `Char`. */ public class CharRange(start: Char, endInclusive: Char) : CharProgression(start, endInclusive, 1), ClosedRange\u0026amp;lt;Char\u0026amp;gt; { override val start: Char get() = first override val endInclusive: Char get() = last override fun contains(value: Char): Boolean = first \u0026lt;= value \u0026amp;\u0026amp; value \u0026lt;= last /** * Checks whether the range is empty. * * The range is empty if its start value is greater than the end value. */ override fun isEmpty(): Boolean = first \u0026gt; last override fun equals(other: Any?): Boolean = other is CharRange \u0026amp;\u0026amp; (isEmpty() \u0026amp;\u0026amp; other.isEmpty() || first == other.first \u0026amp;\u0026amp; last == other.last) override fun hashCode(): Int = if (isEmpty()) -1 else (31 * first.code + last.code) override fun toString(): String = \u0026#34;$first..$last\u0026#34; companion object { /** An empty range of values of type Char. */ public val EMPTY: CharRange = CharRange(1.toChar(), 0.toChar()) } } /** * A range of values of type `Int`. */ public class IntRange(start: Int, endInclusive: Int) : IntProgression(start, endInclusive, 1), ClosedRange\u0026amp;lt;Int\u0026amp;gt; { override val start: Int get() = first override val endInclusive: Int get() = last override fun contains(value: Int): Boolean = first \u0026lt;= value \u0026amp;\u0026amp; value \u0026lt;= last /** * Checks whether the range is empty. * * The range is empty if its start value is greater than the end value. */ override fun isEmpty(): Boolean = first \u0026gt; last override fun equals(other: Any?): Boolean = other is IntRange \u0026amp;\u0026amp; (isEmpty() \u0026amp;\u0026amp; other.isEmpty() || first == other.first \u0026amp;\u0026amp; last == other.last) override fun hashCode(): Int = if (isEmpty()) -1 else (31 * first + last) override fun toString(): String = \u0026#34;$first..$last\u0026#34; companion object { /** An empty range of values of type Int. */ public val EMPTY: IntRange = IntRange(1, 0) } } /** * A range of values of type `Long`. */ public class LongRange(start: Long, endInclusive: Long) : LongProgression(start, endInclusive, 1), ClosedRange\u0026amp;lt;Long\u0026amp;gt; { override val start: Long get() = first override val endInclusive: Long get() = last override fun contains(value: Long): Boolean = first \u0026lt;= value \u0026amp;\u0026amp; value \u0026lt;= last /** * Checks whether the range is empty. * * The range is empty if its start value is greater than the end value. */ override fun isEmpty(): Boolean = first \u0026gt; last override fun equals(other: Any?): Boolean = other is LongRange \u0026amp;\u0026amp; (isEmpty() \u0026amp;\u0026amp; other.isEmpty() || first == other.first \u0026amp;\u0026amp; last == other.last) override fun hashCode(): Int = if (isEmpty()) -1 else (31 * (first xor (first ushr 32)) + (last xor (last ushr 32))).toInt() override fun toString(): String = \u0026#34;$first..$last\u0026#34; companion object { /** An empty range of values of type Long. */ public val EMPTY: LongRange = LongRange(1, 0) } } downTo To iterate over a range in reverse order, we can use downTo operator which is an extension function on different types like Int, Long, Char and provides the reverse iteration with step size as -1.\nval x = 4 for (item in 10 downTo 1){ println(item) } if ((10 downTo 1).contains(x)){ println(\u0026#34;X is in range\u0026#34;) } when (x){ in 10 downTo 1 -\u0026gt; { println(\u0026#34;X is in range\u0026#34;) } } until The until operator can be used to exclude the endElement. The iterator or the if and when condition will not include the end element in case of until.\nval x = 4 for (item in 1 until 10){ println(item) } if ((1 until 10).contains(x)){ println(\u0026#34;X is in range\u0026#34;) } when (x){ in 1 until 10 -\u0026gt; { println(\u0026#34;X is in range\u0026#34;) } } step The step can be used to change the step size of the iteration over the range.\nval x = 4 for (item in 1..10 step 2){ println(item) } if ((1 until 10 step 2).contains(x)){ println(\u0026#34;X is in range\u0026#34;) } when (x){ in 10 downTo 1 step 2 -\u0026gt; { println(\u0026#34;X is in range\u0026#34;) } } ","tags":["Kotlin"],"title":"Kotlin Range Operator"},{"categories":["Blog"],"date":"December 20, 2021","permalink":"https://agrawalsuneet.github.io/blogs/iterators-in-kotlin/","section":"blogs","summary":"Collections (Sets, Maps and Lists) are something we use daily. Traversing (Iteration) is the most common operation we perform over any collection.\nIterators are used to traverse over a collection object. It provides access to the elements of the collection object sequentially without exposing the underlying structure of the collection.\nHow to get an iterator object? An iterator reference object can be obtained using iterator() function which is declared in the Iterable interface for generic type T. The Iterable interface is extended by the Collection interface which is implemented by all immutable Sets, Maps and Lists.\n/** * Classes that inherit from this interface can be represented as a sequence of elements that can * be iterated over. * @param T the type of element being iterated over. The iterator is covariant in its element type. */ public interface Iterable\u0026amp;lt;out T\u0026amp;gt; { /** * Returns an iterator over the elements of this object. */ public operator fun iterator(): Iterator\u0026amp;lt;T\u0026amp;gt; } The Iterable has one more variant interface as MutableIterable which has the same iterator() function but this interface is extended by MutableCollection which is implemented by mutable Sets, Maps and Lists.\n/** * Classes that inherit from this interface can be represented as a sequence of elements that can * be iterated over and that supports removing elements during iteration. * @param T the type of element being iterated over. The mutable iterator is invariant in its element type. */ public interface MutableIterable\u0026amp;lt;out T\u0026amp;gt; : Iterable\u0026amp;lt;T\u0026amp;gt; { /** * Returns an iterator over the elements of this sequence that supports removing elements during iteration. */ override fun iterator(): MutableIterator\u0026amp;lt;T\u0026amp;gt; } How to use an iterator object? The object we get by calling the iterator() function points to the address of the first element of the collection. This is equivalent to the head of a LinkedList. Calling the next function on the iterator object will return the next element of that collection. We also have the hasNext function which returns a boolean if the iteration has more elements.\nIf the collection is empty, the first call to the hasNext function itself will return false. There is no need to handle any null pointer exception.\n/** * An iterator over a collection or another entity that can be represented as a sequence of elements. * Allows to sequentially access the elements. */ public interface Iterator\u0026amp;lt;out T\u0026amp;gt; { /** * Returns the next element in the iteration. */ public operator fun next(): T /** * Returns `true` if the iteration has more elements. */ public operator fun hasNext(): Boolean } Similar to MutableIterable, we have a MutableIterator interface also which extends the Iterator interface and adds another function, remove() which provides the mutability functionality.\n/** * An iterator over a mutable collection. Provides the ability to remove elements while iterating. * @see MutableCollection.iterator */ public interface MutableIterator\u0026amp;lt;out T\u0026amp;gt; : Iterator\u0026amp;lt;T\u0026amp;gt; { /** * Removes from the underlying collection the last element returned by this iterator. */ public fun remove(): Unit } Example using iterator There are three ways to use an iterator on all types of collections.\n1. Using hasNext and next functions Any collection can be iterated using the hasNext and next functions with a while loop.\nBelow are the examples for the same.\n//Map val map = mapOf(1 to \u0026#34;one\u0026#34;, 2 to \u0026#34;two\u0026#34;, 3 to \u0026#34;three\u0026#34;) val mapIterator = map.iterator() while(mapIterator.hasNext()){ val entry = mapIterator.next() println(entry.key.toString() + \u0026#34; : \u0026#34; + entry.value ) } //Set val set = setOf(1,2,3) val setIterator = set.iterator() while(setIterator.hasNext()){ println(setIterator.next()) } //List val list = listOf(1,2,3) val listIterator = list.iterator() while(listIterator.hasNext()){ println(listIterator.next()) } Keep in mind, once the iterator passes through the last element, it can no longer be used for retrieving elements. Neither can it be reset to any previous position. In order to iterate through the collection again, we need to create a new iterator.\n2. Using for-in loop Any collection can also be iterated using a for-in loop.[For-in](blogs/kotlin-for-loop/\u0026quot; target=) doesn\u0026rsquo;t provide us with the iterable object but uses the iterator implicitly.\nBelow are the examples for the same.\n//Map val map = mapOf(1 to \u0026#34;one\u0026#34;, 2 to \u0026#34;two\u0026#34;, 3 to \u0026#34;three\u0026#34;) for(entry in map){ println(entry.key.toString() + \u0026#34; : \u0026#34; + entry.value ) } //Set val set = setOf(1,2,3) for(entry in set){ println(entry) } //List val list = listOf(1,2,3) for(item in list){ println(item) } 3. Using for-each loop Any collection can also be iterated using a for-each loop.[For-each](blogs/kotlin-for-loop/\u0026quot; target=) also doesn\u0026rsquo;t provide us with the iterable object but uses the iterator implicitly.\nBelow are the examples for the same.\n//Map val map = mapOf(1 to \u0026#34;one\u0026#34;, 2 to \u0026#34;two\u0026#34;, 3 to \u0026#34;three\u0026#34;) map.forEach{ entry -\u0026gt; println(entry.key.toString() + \u0026#34; : \u0026#34; + entry.value ) } //Set val set = setOf(1,2,3) set.forEach{ entry -\u0026gt; println(entry) } //List val list = listOf(1,2,3) list.forEach{ item -\u0026gt; println(item) } List Iterators In order to iterate over a list, we have another Iterator ie ListIterator which provides the additional functionality of traversing to the previous element also. It has hasPrevious and previous functions which can be used to traverse in the backward direction.\nListIterator also has nextIndex and previousIndex functions which return the index of the elements.\n/** * An iterator over a collection that supports indexed access. * @see List.listIterator */ public interface ListIterator\u0026amp;lt;out T\u0026amp;gt; : Iterator\u0026amp;lt;T\u0026amp;gt; { // Query Operations override fun next(): T override fun hasNext(): Boolean /** * Returns `true` if there are elements in the iteration before the current element. */ public fun hasPrevious(): Boolean /** * Returns the previous element in the iteration and moves the cursor position backwards. */ public fun previous(): T /** * Returns the index of the element that would be returned by a subsequent call to [next]. */ public fun nextIndex(): Int /** * Returns the index of the element that would be returned by a subsequent call to [previous]. */ public fun previousIndex(): Int } Since ListIterator can be used to iterate in both the directions, it can be used even after reaching the last element.\nBelow is the example for the same.\n//List val list = listOf(1,2,3,4) val listIterator = list.listIterator() while (listIterator.hasNext()){ println(\u0026#34;Index : ${listIterator.nextIndex() } ; Element : ${listIterator.next()}\u0026#34;) } while (listIterator.hasPrevious()){ println(\u0026#34;Index : ${listIterator.previousIndex() } ; Element : ${listIterator.previous()}\u0026#34;) } Mutable List Iterators In order to iterate over mutable list collection, we have another Iterator ie MutableListIterator which provides the additional functionality of adding, editing or removing to the existing collection while iteration itself. MutableListIterator extends ListIterator as well as MutableIterator.\n/** * An iterator over a mutable collection that supports indexed access. Provides the ability * to add, modify and remove elements while iterating. */ public interface MutableListIterator\u0026amp;lt;T\u0026amp;gt; : ListIterator\u0026amp;lt;T\u0026amp;gt;, MutableIterator\u0026amp;lt;T\u0026amp;gt; { // Query Operations override fun next(): T override fun hasNext(): Boolean // Modification Operations override fun remove(): Unit /** * Replaces the last element returned by [next] or [previous] with the specified element [element]. */ public fun set(element: T): Unit /** * Adds the specified element [element] into the underlying collection immediately before the element that would be * returned by [next], if any, and after the element that would be returned by [previous], if any. * (If the collection contains no elements, the new element becomes the sole element in the collection.) * The new element is inserted before the implicit cursor: a subsequent call to [next] would be unaffected, * and a subsequent call to [previous] would return the new element. (This call increases by one the value \\ * that would be returned by a call to [nextIndex] or [previousIndex].) */ public fun add(element: T): Unit } Below is the example for the same. //List val list = mutableListOf(1,2,3,4) val mutableIterator = list.listIterator() mutableIterator.next() mutableIterator.add(0) println(list) mutableIterator.next() mutableIterator.remove() println(list) mutableIterator.next() mutableIterator.set(10) println(list) ","tags":["Kotlin"],"title":"Iterators in Kotlin"},{"categories":["Blog"],"date":"October 5, 2021","permalink":"https://agrawalsuneet.github.io/blogs/swift-range-operators/","section":"blogs","summary":"Range Operator in Swift is a basic operator that is used to operate over a range. There are multiple types of range operators where we can include or exclude the upper range. Or we can start the range with some value or can end before some max value. The range operators can be used with for loops, if conditions, switch conditions or even in array iteration. First, let to see a basic example of a range operator.\nA basic range operator can be defined with ... having a lower range value to the left side and upper range value to the right side of ...\n//For-in loop for pos in 0...5 { print(pos) } //If condition if (0...5).contains(value){ print(\u0026#34;between 0 to 5\u0026#34;) } //Switch operator let value = 5 switch(value){ case 0...5: print(\u0026#34;between 0 to 5\u0026#34;) default: print(\u0026#34;less than 0 or greater than 5\u0026#34;) } //Array iteration let numbers = [\u0026#34;One\u0026#34;, \u0026#34;Two\u0026#34;, \u0026#34;Three\u0026#34;, \u0026#34;Four\u0026#34;, \u0026#34;Five\u0026#34;] for number in numbers[1...3] { print(number) } Now that we understood the very basic use cases of the range operators, let\u0026rsquo;s try to understand its types.\nThere are 3 types of range operators Closed Range Operator Half-Open Range Operator One-Sided Range Operator Lets try to understand them one by one with example.\nClosed Range Operator The closed range operator operates from an initial value say a to a final value say b including both the values (a...b). The syntax for that would be\nfor pos in 0...5 { print(pos) } The minimum criteria for closed range operator is the initial value should be less then or equal to the upper value else this will throw a run time error as below.\nerror: Fatal error: Range requires lowerBound \u0026lt;= upperBound Half-Open Range Operator The half range operator operates from an initial value say a to a final value say b excluding the final value (a..\u0026lt;b). This is most useful when we work with zero-based lists such as arrays. The syntax for that would be\nlet numbers = [\u0026#34;One\u0026#34;, \u0026#34;Two\u0026#34;, \u0026#34;Three\u0026#34;, \u0026#34;Four\u0026#34;, \u0026#34;Five\u0026#34;] for pos in 0..\u0026lt;numbers.count { print(\u0026#34;Item at \\(pos) is \\(numbers[pos])\u0026#34;) } The same criteria of having a lower value should be less or equal to the upper value exist for half range operator also but if both lower and upper values are same, there will be no run time error but it will an empty statement or the condition will be false.\nOne-Sided Range Operator The one-sided range operator is a special type of range operator where we skip either initial value or final value in case of closed range and we can skip only the initial value in case of half-open range.\nLet\u0026rsquo;s understand it with the below example.\nTo make a closed range to a one-sided range, we can skip either the initial value or the final value.\nlet numbers = [\u0026#34;One\u0026#34;, \u0026#34;Two\u0026#34;, \u0026#34;Three\u0026#34;, \u0026#34;Four\u0026#34;, \u0026#34;Five\u0026#34;] for number in numbers[...2] { print(number) //this will print One, Two and Three only } for number in numbers[2...] { print(number) //this will print Three, Four and Five only } To make a half-open range to a one-sided range, we can skip the initial value.\nlet numbers = [\u0026#34;One\u0026#34;, \u0026#34;Two\u0026#34;, \u0026#34;Three\u0026#34;, \u0026#34;Four\u0026#34;, \u0026#34;Five\u0026#34;] for number in numbers[..\u0026lt;2] { print(number)r //this will print One and Two only } All the above three types of range operators can be used with loops, if conditions, array iterations and even with switch cases statements according to the use cases.\n","tags":["Swift"],"title":"Swift Range Operators"},{"categories":["Blog"],"date":"September 10, 2021","permalink":"https://agrawalsuneet.github.io/blogs/swift-for-loop/","section":"blogs","summary":"For loops are used by every developer regularly. There is for-in as well as a for-each loop in Swift which has a bit different syntaxes. Both of them are used to iterate over a range, array, set or dictionary but have a bit different syntaxes.\nWhile comparing with other languages, I realized in Swift, there are few concepts which are completely different from java or any other another language for loops.\nWait! They are not this tough. In fact, they are very easy, interesting and helpful.\nLet’s check one by one.\n1. Simple for loop in java that iterates from some number to some number incrementing one on each loop pass. /*Java code*/ for (int i = 0; i \u0026lt;= 10; i++){ System.out.print(i); } its equivalent Swift code\n/*Swift code*/ for i in 1...10 { print(i) } Things to notice No need to declare the data type of variable. If iterating over a range, we can use ... (closed range) operator. The lower and upper (including) limit can be defined on both the sides of ... operator. 2. Now let’s say if I don’t don’t want to include the upper limit in the loop and break the loop if it hits the upper limit. /*Java code*/ for (int j = 0; j \u0026lt; 10; j++) { System.out.print(j); //this will print only up to 9 } We can use the half-open range operator (..\u0026lt;).\n/*Swift code*/ for i in 1..\u0026amp;lt;10 { print(i) } 3. I want to increment it by 2 or some other number. /*Java code*/ for (int i = 0; i \u0026lt;= 10; i += 2) { System.out.print(i); } We can use stride function here\n/*Swift code*/ for i in stride(from: 0, through: 10, by: 2) { print(i) } //this will run till last value, in our case till 10 for i in stride(from: 0, to: 10, by: 2) { print(i) } //this will run less then last value, in our case till 8 4. Wait, what if I want to run the loop in reverse order. Can I use 10...1 ? /*Java code*/ for (int i = 10; i \u0026gt; 0; i--) { System.out.print(i); } No, you can not use 10...1 directly as ... operator never works on the reverse ranges.\nIt will give you below run time error.\n//Error error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). The process has been left at the point where it was interrupted, use \u0026#34;thread return -x\u0026#34; to return to the state before expression evaluation. You have to use reversed() function.\n/*Swift code*/ for i in (0...10).reversed() { print(i) } You can also change the step size with stride function.\n/*Java code*/ for (int i = 10; i \u0026gt; 0; i -= 2) { System.out.print(i); } /*Swift code*/ for i in stride(from: 0, to: 10, by: 2).reversed() { print(i) } for i in stride(from: 0, through: 10, by: 2).reversed() { print(i) } But please note that stride function overload to and through works on upper range, in both nomral as well as in reversed case.\n5. What if I have a complex calculation instead of addition or subtraction in each step. Let’s say multiplication or division. /*Java code*/ for (int k = 2; k \u0026lt;= 256; k *= 2) { System.out.print(k); } Move to while loop, no other way\n/*Swift code*/ var k = 2 while (k \u0026lt;= 256) { print(k) k *= 2 } 6. I want to iterate over an array now. /*Java code*/ int[] arr = new int[5]; for (int item: arr) { System.out.print(item); } Simple, use the in in Swift\n/*Swift code*/ let arr = [0,1,2,3,4] for element in arr { print(element) } 7. I want to use the position (index) also. How can I do that? /*Java code*/ int[] arr = new int[5]; for (int i = 0; i \u0026lt; arr.length; i++) { System.out.print(arr[i]); } Just use enumerated function.\n/*Swift code*/ let arr = [0,1,2,3,4] for (index, element) in arr.enumerated() { print(\u0026#34;The element at \\(index) is \\(element)\u0026#34;) } 8. I heard about some for foreach also. Can I use the same in Swift? /*Java code*/ let arr = [0,1,2,3,4] for element in arr { print(element) } Just use foreach function.\n/*Swift code*/ let arr = [0,1,2,3,4] arr.forEach{ element in print(element) } 9. And what about Dicionary? /*Java code*/ HashMap\u0026lt;String,String\u0026gt; map = new HashMap(); map.put(\u0026#34;Suneet\u0026#34;,\u0026#34;Engineering\u0026#34;); map.put(\u0026#34;Ballu\u0026#34;,\u0026#34;Sales\u0026#34;); map.put(\u0026#34;John\u0026#34;,\u0026#34;Marketing\u0026#34;); for (Map.Entry\u0026lt;String, String\u0026gt; entry : map.entrySet()) { System.out.println(entry.getKey() + \u0026#34; is working in \u0026#34; + entry.getValue()); } Simple. Use in based iteration.\n/*Swift code*/ let employee = [\u0026#34;Suneet\u0026#34;: \u0026#34;Engineering\u0026#34;, \u0026#34;Ballu\u0026#34;: \u0026#34;Sales\u0026#34;, \u0026#34;John\u0026#34;: \u0026#34;Marketing\u0026#34;] for (name, department) in employee { print(\u0026#34;\\(name) is working in \\(department) department\u0026#34;) } No, I am a fan of foreach loop.\nOk, no problem, there you go.\n/*Swift code*/ let employee = [\u0026#34;Suneet\u0026#34;: \u0026#34;Engineering\u0026#34;, \u0026#34;Ballu\u0026#34;: \u0026#34;Sales\u0026#34;, \u0026#34;John\u0026#34;: \u0026#34;Marketing\u0026#34;] employee.forEach { name, department in print(\u0026#34;\\(name) is working in \\(department) department\u0026#34;) } And we are done. See I told you this will be very easy and interesting.\n","tags":["Swift"],"title":"Swift ‘For’ loop"},{"categories":["Blog"],"date":"September 5, 2021","permalink":"https://agrawalsuneet.github.io/blogs/lazy-property-in-swift/","section":"blogs","summary":"Object creation is a heavy process. When we create a class object, all the public and private properties of that class are initialised inside the constructor. Every variable inside a class initialisation requires a certain amount of time to allocate the memory on the heap and hold its reference on the stack. The more variables, the more time it may take but since the time is in microseconds or even less, it\u0026rsquo;s not observable.\nSometimes we don\u0026rsquo;t need all the objects to be initialised during the class object creation itself.\nThere can be two reasons for that.\nThat object/property/variable is dependent on another object to initialise first and use its reference. The flow is such that we need that object only in a certain condition. In Swift, we have certain features which can help us in delaying that object initialisation as per the requirement.\nOne way of doing that is using lazy initialization.\nLazy initialisation is also denoted as lazy var in Swift.\nlazy initialisation is a delegation of object creation when the first time that object will be called. The reference will be created but the object will not be created. The object will only be created when the first time that object will be accessed and every next time the same reference will be used.\nThe basic initialisation of lazy property in a User struct object by using lazy will look like below\nstruct User { let name : String let age : Int } struct Department { var users : [User] init(users : [User]) { print(\u0026#34;Department constructor is called\u0026#34;) self.users = users } lazy var youngestUser : User? = { print(\u0026#34;Department youngestUser is computed\u0026#34;) return self.users.min(by: {$0.age \u0026lt; $1.age}) }() } Let\u0026rsquo;s try to understand what exactly lazy is Lazy initialisation is a delegation of property initialisation that will only be called when that property will be used the first time.\nEven if we initialise the struct or class object, the lazy property will not be set.\nLets see this with an example.\nstruct User { let name : String let age : Int } struct Department { var users : [User] init(users : [User]) { print(\u0026#34;Department constructor is called\u0026#34;) self.users = users } lazy var youngestUser : User? = { print(\u0026#34;Department youngestUser is computed\u0026#34;) return self.users.min(by: {$0.age \u0026lt; $1.age}) }() } var engineeringDepartment = Department(users: [ User(name: \u0026#34;Suneet\u0026#34;, age: 29), User(name: \u0026#34;Ballu\u0026#34;, age: 20), User(name: \u0026#34;Agrawal\u0026#34;, age: 50) ]) //This will print: Department constructor is called print(engineeringDepartment.youngestUser ?? \u0026#34;\u0026#34;) //This will print: Department youngestUser is computed //followed by : User(name: \u0026#34;Ballu\u0026#34;, age: 20) As we can see the lazy property was not initialised even when we initialised the Department struct object. That only got initialised when we called the lazy property for the first time.\nThings to keep in mind while working with lazy property Can only be used with var lazy can only be used with var but it can\u0026rsquo;t be used with a let (immutable) property.\nstruct Department { //... lazy let youngestUser : User? = { \u0026lt;e\u0026gt;//\u0026#39;lazy\u0026#39; cannot be used on a let\u0026lt;/e\u0026gt; return self.users.min(by: {$0.age \u0026lt; $1.age}) }() } Can be of primitive or non-primitive type A lazy property can be of primitive or non-primitive type.\nstruct Department { //... lazy var youngestUserAge : Int? = { return self.users.min(by: {$0.age \u0026lt; $1.age})?.age }() lazy var youngestUser : User? = { return self.users.min(by: {$0.age \u0026lt; $1.age}) }() } Can only be used inside a class or struct Lazy can only be used inside a class or struct. We can\u0026rsquo;t define it in a function or at the root level of a playground file.\nlazy var youngestUser : Int = { \u0026lt;e\u0026gt;//Lazy is only valid for members of a struct or class\u0026lt;/e\u0026gt; return 1 }() The struct or class object accessing lazy property should also be var The object which is trying to access the lazy property should also be mutable means var.\nstruct Department { //... lazy var youngestUser : User? = { print(\u0026#34;Department youngestUser is computed\u0026#34;) return self.users.min(by: {$0.age \u0026lt; $1.age}) }() } let engineeringDepartment = Department(users: [ User(name: \u0026#34;Suneet\u0026#34;, age: 29), User(name: \u0026#34;Ballu\u0026#34;, age: 20), User(name: \u0026#34;Agrawal\u0026#34;, age: 50) ]) print(engineeringDepartment.youngestUser ?? \u0026#34;\u0026#34;) \u0026lt;e\u0026gt;//Cannot use mutating getter on immutable value: \u0026#39;engineeringDepartment\u0026#39; is a \u0026#39;let\u0026#39; constant\u0026lt;/e\u0026gt; Please note that it\u0026rsquo;s not compulsory to create all the objects of that class or struct should be var but in order to access the lazy property, the variable should be var (mutable) type.\nOnce the value is computed, it will not change until the constructor is called again The computation of the lazy property will only happen once. Later the same values will be returned without computation.\nvar engineeringDepartment = Department(users: [ User(name: \u0026#34;Suneet\u0026#34;, age: 29), User(name: \u0026#34;Ballu\u0026#34;, age: 20), User(name: \u0026#34;Agrawal\u0026#34;, age: 50) ]) print(engineeringDepartment.youngestUser ?? \u0026#34;\u0026#34;) //This will print: User(name: \u0026#34;Ballu\u0026#34;, age: 20) engineeringDepartment.users.append(User(name: \u0026#34;John\u0026#34;, age: 18)) //or engineeringDepartment.users = [User(name: \u0026#34;John\u0026#34;, age: 18)] print(engineeringDepartment.youngestUser ?? \u0026#34;\u0026#34;) //This will still print: User(name: \u0026#34;Ballu\u0026#34;, age: 20) As we can see, even if changed values in the users array or even initialised the array again, the lazy property is still holding the last values.\nThe lazy property will only be computed again when the Department constructor will be called on same object else the lazy property will hold the same values.\nFew things to remember about lazy property A lazy property is used to delay the initialisation of property and it will be initialised only when the first time that property will be called but it will only be called once. Later it will return the same values.\nAlso, it can only be used inside a class or struct and the calling object should also be var.\n","tags":["Swift"],"title":"lazy Property in Swift"},{"categories":["Blog"],"date":"August 29, 2021","permalink":"https://agrawalsuneet.github.io/blogs/lateinit-vs-lazy-property-in-kotlin/","section":"blogs","summary":"Since object creation is a heavy process as it initialises all the public and private properties defined in that class when the constructor is called, Kotlin has few ways to initialise properties later when required. We already discussed lateinit properties and lazy properties.\nLet\u0026rsquo;s try to understand some basic differences between then and when to use what. But before that let\u0026rsquo;s quickly recap the lateinit and lazy properties\nlateinit property lateinit properties are the var properties that can be initialised later in the constructor or in any function according to the use.\ndata class User (val id : Long, val username : String) : Serializable lateinit var lateinitUser : User lazy property lazy properties are the val properties that can also be initialised later when they are called the first time.\nval lazyUser : User? by lazy { User(id = 1, username = \u0026#34;agrawalsuneet\u0026#34;) } Now lets try to understand difference between them. lateinit var whereas lazy val lateinit can only be used with a var property whereas lazy will always be used with val property.\nA lateinit property can be reinitialised again and again as per the use whereas the lazy property can only be initialised once.\nlateinit var lateinitUser : User val lazyUser : User? by lazy { User(id = 1, username = \u0026#34;agrawalsuneet\u0026#34;) } lateinit can\u0026rsquo;t have custom getter or setter whereas lazy has custom getter A lateinit property can\u0026rsquo;t have a custom getter whereas a lazy property has a block that gets executed whenever the first time that property is called.\nval lazyUser : User by lazy { //can do other initialisation here User(id = 1, username = \u0026#34;agrawalsuneet\u0026#34;) } isInitialized In order to check if a lateinit property is initialised or not, we can use the extension function to KProperty directly which returns a boolean if the property is initialised or not.\n/** * Returns `true` if this lateinit property has been assigned a value, and `false` otherwise. * * Cannot be used in an inline function, to avoid binary compatibility issues. */ @SinceKotlin(\u0026#34;1.2\u0026#34;) @InlineOnly inline val @receiver:AccessibleLateinitPropertyLiteral KProperty0\u0026lt;*\u0026gt;.isInitialized: Boolean get() = throw NotImplementedError(\u0026#34;Implementation is intrinsic\u0026#34;) println(::lateinitUser.isInitialized) Since the lazy block returns an object which implements the Lazy interface, we can check if the variable is initialised or not in the case of the lazy property also but for that, we need to split the lazy call.\nval lazyUserDelegate = lazy { User(id = 1, username = \u0026#34;agrawalsuneet\u0026#34;) } val lazyUser by lazyUserDelegate println(lazyUserDelegate.isInitialized()) Primitive types lateinit properties can\u0026rsquo;t be of primitive data types whereas lazy properties can be of primitive date types also.\nlateinit var lateinitInt : Int \u0026lt;e\u0026gt;//compilation error: \u0026#39;lateinit\u0026#39; modifier is not allowed on properties of primitive types\u0026lt;/e\u0026gt; val lazyInt by lazy { 10 } Thread Safety We can\u0026rsquo;t define the thready safety in case of lateinit property but in case of lazy, we can choose between SYNCHRONIZED, PUBLICATION and NONE.\nval lazyUser : User? by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { User(id = 1, username = \u0026#34;agrawalsuneet\u0026#34;) } Nullable Type A lazy property can be of nullable type but a lateinit property can\u0026rsquo;t be of nullable type.\nlateinit var lateinitUser : User? \u0026lt;e\u0026gt;//compilation error: \u0026#39;lateinit\u0026#39; modifier is not allowed on properties of nullable types\u0026lt;/e\u0026gt; val lazyUser : User? by lazy { User(id = 1, username = \u0026#34;agrawalsuneet\u0026#34;) } Accessing before initialisation Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn’t been initialized.\nWe can\u0026rsquo;t ever access a lazy property before it hased been initialised. Remember that the lazy property can be null but the initialisation will still happen when the first time the property will be called.\nBased on the above difference we can decide when to use the lateinit property or when to use the lazy property. The developer doesn\u0026rsquo;t have to remember if the property is initialised or not in case of lazy property but in case of lateinit we need to remember the flow.\nThere are no guidelines in order to decide when to use what but according to the use case, we can decide.\n","tags":["Kotlin"],"title":"lateinit vs lazy Property in Kotlin"},{"categories":["Blog"],"date":"August 4, 2021","permalink":"https://agrawalsuneet.github.io/blogs/lazy-property-in-kotlin/","section":"blogs","summary":"Object creation is a heavy process. When we create a class object, all the public and private properties of that class are initialised inside the constructor. Every variable inside a class initialisation requires a certain amount of time to allocate the memory on the heap and hold its reference on the stack. The more variables, the more time it may take but since the time is in microseconds or even less, it\u0026rsquo;s not observable.\nSometimes we don\u0026rsquo;t need all the objects to be initialised during the class object creation itself.\nThere can be two reasons for that.\nThat object/property/variable is dependent on another object to initialise first and use its reference. The flow is such that we need that object only in a certain condition. In Kotlin, we have certain features which can help us in delaying that object initialisation as per the requirement.\nOne way to do that is by using lateinit Property where we just declare the object/property and its type but didn\u0026rsquo;t initialise it.\nThe drawbacks with lateinit var is\nIts var that means it\u0026rsquo;s mutable We (developer) need to remember to initialise it. We can\u0026rsquo;t have a custom getter to the lateinit property We have another way also to delay the initialisation of a property ie by using lazy initialisation.\nlazy initialisation is a delegation of object creation when the first time that object will be called. The reference will be created but the object will not be created. The object will only be created when the first time that object will be accessed and every next time the same reference will be used.\nThe basic initialisation of a User class object by using lazy will look like below\ndata class User(val id : Long, val username : String) val user : User by lazy { //can do other initialisation here User(id = 1001, username = \u0026#34;ballu\u0026#34;) } Let\u0026rsquo;s try to understand what exactly lazy is lazy is a function defined in kotlin package which takes a lambda or higher-order function as a parameter and returns Lazy\u0026lt;T\u0026gt; object.\nThe passed lambda or higher-order function should return the object of Template class (T).\n/** * Creates a new instance of the [Lazy] that uses the specified initialization function [initializer] * and the default thread-safety mode [LazyThreadSafetyMode.SYNCHRONIZED]. * * If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access. * * Note that the returned instance uses itself to synchronize on. Do not synchronize from external code on * the returned instance as it may cause accidental deadlock. Also this behavior can be changed in the future. */ public actual fun \u0026lt;T\u0026gt; lazy(initializer: () -\u0026gt; T): Lazy\u0026lt;T\u0026gt; = SynchronizedLazyImpl(initializer) The return type of the above lazy function is a Lazy interface reference object which is also defined in kotlin package. This Lazy reference object server as a delegate for implementation of lazy property.\nThe first call to property\u0026rsquo;s get() executes the lambda passed to the lazy function and remembers the result. Any subsequent calls to get the property simply return the remembered result.\n/** * Represents a value with lazy initialization. * * To create an instance of [Lazy] use the [lazy] function. */ public interface Lazy\u0026lt;out T\u0026gt; { /** * Gets the lazily initialized value of the current Lazy instance. * Once the value was initialized it must not change during the rest of lifetime of this Lazy instance. */ public val value: T /** * Returns `true` if a value for this Lazy instance has been already initialized, and `false` otherwise. * Once this function has returned `true` it stays `true` for the rest of lifetime of this Lazy instance. */ public fun isInitialized(): Boolean } Let\u0026rsquo;s look at the thread-safety of lazy property By default, the lazy property is synchronised or thread-safe. That means only a single thread will compute its value and all threads will use the same value. But there is an overload to the lazy function where we can pass the LazyThreadSafetyMode also.\n/** * Creates a new instance of the [Lazy] that uses the specified initialization function [initializer] * and thread-safety [mode]. * * If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access. * * Note that when the [LazyThreadSafetyMode.SYNCHRONIZED] mode is specified the returned instance uses itself * to synchronize on. Do not synchronize from external code on the returned instance as it may cause accidental deadlock. * Also this behavior can be changed in the future. */ public actual fun \u0026lt;T\u0026gt; lazy(mode: LazyThreadSafetyMode, initializer: () -\u0026gt; T): Lazy\u0026lt;T\u0026gt; = when (mode) { LazyThreadSafetyMode.SYNCHRONIZED -\u0026gt; SynchronizedLazyImpl(initializer) LazyThreadSafetyMode.PUBLICATION -\u0026gt; SafePublicationLazyImpl(initializer) LazyThreadSafetyMode.NONE -\u0026gt; UnsafeLazyImpl(initializer) } LazyThreadSafetyMode is an enum class with values as below\n/** * Specifies how a [Lazy] instance synchronizes initialization among multiple threads. */ public enum class LazyThreadSafetyMode { /** * Locks are used to ensure that only a single thread can initialize the [Lazy] instance. */ SYNCHRONIZED, /** * Initializer function can be called several times on concurrent access to uninitialized [Lazy] instance value, * but only the first returned value will be used as the value of [Lazy] instance. */ PUBLICATION, /** * No locks are used to synchronize an access to the [Lazy] instance value; if the instance is accessed from multiple threads, its behavior is undefined. * * This mode should not be used unless the [Lazy] instance is guaranteed never to be initialized from more than one thread. */ NONE, } All 3 types are explained by themselves.\nSYNCHRONIZED is used to ensure thread safety. Only a single thread will initialise the value and it uses lock to ensure the same. PUBLICATION can be called several times but the returned value will be used. NONE is a tricky one and not suggested to use until for a specific reason. no locks are used and if accessed from multiple threads its behaviour is undefined. By default the lazy function uses SYNCHRONIZED but we can change it by passing it as a parameter to the lazy function.\nval user : User by lazy(LazyThreadSafetyMode.PUBLICATION) { //can do other initialisation here User(id = 1001, username = \u0026#34;ballu\u0026#34;) } Few things to remember about lazy property Every lazy property is a val (immutable) property and cannot be changed once assigned. The property initialisation is conditional based and will only be initialised when it will be called the first time. By default, the property initialisation is thread-safe. We can do other computations also before initialising the actual property in the same lazy function. ","tags":["Kotlin"],"title":"lazy Property in Kotlin"},{"categories":["Blog"],"date":"June 26, 2021","permalink":"https://agrawalsuneet.github.io/blogs/native-android-receive-text-from-other-apps-in-unity/","section":"blogs","summary":"In continuation to my previous blog Native Android text sharing in Unity, where we learnt about sharing text from a Unity app targeting the Android platform, let\u0026rsquo;s try to learn about how can we receive a text from other apps. Accepting a text from other apps is not that common but sometimes location-based games required to accept text or location shared from other apps. There can be a generic use case also where we want to accept some text from other apps for any purpose.\nIf you have not read the previous blogs, I would strongly recommend to read them first. You can read them on the links below.\nNative Android in Unity Native Android text sharing in Unity Custom Android Manifest File in Unity Android provides a native share functionality to handle text or multimedia sharing. Any app can trigger an intent along with extra params to share a text. To receive the text or show our app in the sharing intent list handled by Android, we majorly have to do two things.\nRegister Intent Filter in Manifest file. Extract text from the Intent object shared by the other app. Register Intent Filter in Manifest file The Android manifest file describes essential information about your app to the Android build tools, the Android operating system, and Google Play. Every Android app or unity app running on the Android platform must have a Manifest file. The manifest file contains information about package name, permissions, application name, icon, activities, services, providers and much more.\nTo add an intent filter to the manifest file in an activity tag, first, we need to add a custom manifest file. We can add a custom manifest file and Unity will generate a merged manifest file at the end which will be shipped along with the final apk generated.\nWe can copy a basic structure of the custom manifest file from /Temp/StagingArea/AndroidManifest.xml\nAnd can paste the modified AndroidManifest.xml at Assests/Plugins/Android/AndroidManifest.xml\nPlease note that if this file doesn\u0026rsquo;t exist for you, change the target platform to Android and build the Unity project once. It will generate the Temp folder and this file inside it. This is a temporary file that is created by Unity but we can copy it.\nThe copied manifest file will be of xml format and will look like something below.\nTo enable accepting text from other apps, we need to add an Intent Filter to the activity tag. There can be multiple activity tags but there will at least be one activity tag with the name com.unity3d.player.UnityPlayerActivity.\nThat will also contain one intent-filter tag already with category android.intent.category.LAUNCHER\nWe need to add one more as below.\n\u0026lt;intent-filter\u0026gt; \u0026lt;action android:name=\u0026#34;android.intent.action.SEND\u0026#34; /\u0026gt; \u0026lt;category android:name=\u0026#34;android.intent.category.DEFAULT\u0026#34; /\u0026gt; \u0026lt;data android:mimeType=\u0026#34;text/plain\u0026#34; /\u0026gt; \u0026lt;/intent-filter\u0026gt; To understand what is intent filter and why we added this, we need to understand what is Intent first.\nAn Intent is a messaging object which is used to start an activity, a service or deliver a broadcast.\nIntent is of two types Explicit Intent : An explicit intent is one that you use to launch a specific app component, such as a particular activity or service in your app. Implicit Intent : An implicit intent specifies an action that can invoke any app on the device able to perform the action. Any app sharing the text will be triggering an implicit action. In other to catch that implicit intent triggered by other apps we need to define an intent filter in the manifest file as we did along with category, action and data tags.\nThe final manifest file will look like below.\nExtract text from the Intent object shared by the other app This is a straightforward part. We need to get the reference of the current activity, get the intent out of it and simply get the extra text out of it.\nIf you read the previous blog Native Android in Unity, you can easily understand how can we get the current activity reference and the context object.\n//create a class reference of unity player activity AndroidJavaClass unityActivity = new AndroidJavaClass (\u0026#34;com.unity3d.player.UnityPlayer\u0026#34;); //get the context of current activity AndroidJavaObject context = unityActivity.GetStatic\u0026lt;AndroidJavaObject\u0026gt; (\u0026#34;currentActivity\u0026#34;); To get the intent object, we just need to call getIntent on the content object. And later we can get the string extra using getStringExtra on the intent object which will return the string shared by other apps.\n//get the current intent object AndroidJavaObject intent = context.Call\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;getIntent\u0026#34;); //get the extra text from intent string incomingText = intent.Call\u0026lt;string\u0026gt;(\u0026#34;getStringExtra\u0026#34;, \u0026#34;android.intent.extra.TEXT\u0026#34;); The overall code will look like below.\nWe can attach the above script to any game object and extract the text shared by other apps.\n","tags":["Unity","CSharp"],"title":"Native Android Receive Text from Other Apps in Unity"},{"categories":["Blog"],"date":"May 29, 2021","permalink":"https://agrawalsuneet.github.io/blogs/custom-android-manifest-file-in-unity/","section":"blogs","summary":"The Android manifest file describes essential information about your app to the Android build tools, the Android operating system, and Google Play. Every Android app or unity app running on the Android platform must have a Manifest file. The manifest file contains information about package name, permissions, application name, icon, activities, services, providers and much more.\nUsually, Unity takes care of this manifest file generation and putting it in the right place but sometimes we need to add some custom tags to the final generated manifest file like adding intent-filters to the activity tag.\nWe can add a custom manifest file and Unity will generate a merged manifest file at the end which will be shipped along with the final apk generated.\nWe can copy a basic structure of the custom manifest file from /Temp/StagingArea/AndroidManifest.xml\nAnd can paste the modified AndroidManifest.xml at Assests/Plugins/Android/AndroidManifest.xml\nPlease note that if this file doesn\u0026rsquo;t exist for you, change the target platform to Android and build the Unity project once. It will generate the Temp folder and this file inside it. This is a temporary file that is created by Unity but we can copy it.\nThe AndroidManifest.xml for a new hello world project in unity looks like the below one but I will suggest you create your own and copy that instead of using the below one.\nThe final output file will be a merge of one created by Unity and the one we pasted at Assests/Plugins/Android/AndroidManifest.xml\nNow we can modify it according to our need like we can add intent-filters to it and that will be available in the final Manifest file generated by Unity.\n","tags":["Unity"],"title":"Custom Android Manifest File in Unity"},{"categories":["Blog"],"date":"May 29, 2021","permalink":"https://agrawalsuneet.github.io/blogs/lerp-function-unity/","section":"blogs","summary":"In game development, one of the most common problems is the smooth transition of objects from one position to another. A linear interpolation or Lerp function is a popular technique used to achieve this in Unity. In this blog post, we will explore the lerp function in Unity and its implementation.\nWhat is Lerp Function? The Lerp function stands for linear interpolation.\nThe function returns a value that is a linear interpolation between the starting and ending values, based on the weight parameter. It takes three arguments:\nThe starting value The end value A weight between 0 and 1 representing the percentage of the value between the start and end values. In case of linear transformation, the Lerp function calculates the position along the line that corresponds to the input value. When the input value is 0, the function returns the starting position, and when the input value is 1, it returns the target position. For values between 0 and 1, it returns a position that is between the two endpoints.\nImplementation of Lerp Function Unity provides a built-in Lerp function that can be used to interpolate between two positions. The function is called Lerp and can be called using the following syntax:\nVector3.Lerp(startPosition, targetPosition, t); This function takes the startingPosition, targetPosition, and a value t between 0 and 1 representing the percentage of the distance between the two positions. It returns the position that is t percent of the way from the starting position to the target position.\nTransform example using Lerp function Suppose we have an object that we want to move from its current position to a new position over a period of 2 seconds. We can use the Lerp function to achieve this by calculating the position of the object at each frame using the following code:\npublic Transform target; public float speed = 0.5f; private float startTime; private float journeyLength; void Start() { startTime = Time.time; journeyLength = Vector3.Distance(transform.position, target.position); } void Update() { float distCovered = (Time.time - startTime) * speed; float fracJourney = distCovered / journeyLength; transform.position = Vector3.Lerp(transform.position, target.position, fracJourney); } In this example, we store the target position in the target variable and the speed at which we want to move the object in the speed variable.\nIn the Start function, we calculate the distance between the current position of the object and the target position and store it in the journeyLength variable.\nIn the Update function, we calculate the distance covered by the object at each frame using the distCovered variable. We then calculate the fraction of the journey completed using the fracJourney variable. Finally, we use the Lerp function to move the object from its current position to the target position based on the fraction of the journey completed.\nSmooth camera movement using Lerp function Suppose we have a camera in ourr game that follows the player\u0026rsquo;s movements. we can use the Lerp function to smoothly interpolate between the camera\u0026rsquo;s current position and the player\u0026rsquo;s position, creating a smooth camera movement effect.\nfractionTime can be calculated using the duration over which the transition needs to happen and the time lapsed. This value should be between 0 to 1.\n// Smoothly move the camera towards the player\u0026#39;s position Vector3 targetPosition = player.transform.position; Vector3 currentPosition = transform.position; //Update function transform.position = Vector3.Lerp(currentPosition, targetPosition, fractionTime); Color Transition using Lerp function We can use the Lerp function to create smooth transitions between different colors. For example, suppose we want to change the color of a material over time. we can use the Lerp function to smoothly interpolate between the current color and the target color.\nfractionTime can be calculated using the duration over which the transition needs to happen and the time lapsed. This value should be between 0 to 1.\n// Smoothly transition the color of a material Material material = GetComponent\u0026lt;Renderer\u0026gt;().material; Color currentColor = material.color; Color targetColor = Color.red; //Update function material.color = Color.Lerp(currentColor, targetColor, fractionTime); Interpolation between values using Lerp function The Lerp function can also be used to interpolate between different values, such as floats or integers. For example, suppose we have a variable that represents the player\u0026rsquo;s health. we can use the Lerp function to smoothly interpolate between the current health value and the target health value.\nfractionTime can be calculated using the duration over which the transition needs to happen and the time lapsed. This value should be between 0 to 1.\n// Smoothly interpolate the player\u0026#39;s health float currentHealth = player.health; float targetHealth = 100; //Update function player.health = Mathf.Lerp(currentHealth, targetHealth, fractionTime); Conclusion The Lerp function is a versatile and powerful tool in Unity that can be used to create smooth animations and transitions. By understanding how the function works and experimenting with different parameters, we can create a wide variety of effects in our game.\nIt can be used for multiple things like\nSmooth movement of a game object from one position to another position. Smooth movement of camera with player. Smooth transition from one color to another. Interpolation between any two values over a certain period of time. ","tags":["Unity"],"title":"Lerp Function : Unity"},{"categories":["Blog"],"date":"May 28, 2021","permalink":"https://agrawalsuneet.github.io/blogs/typecast-android-object-in-unity/","section":"blogs","summary":"In continuation to previous my previous blogs, where we learnt about how can we use AndroidJavaClass and AndroidJavaObject to achieve simple native Android functionality in Unity, We will move one step ahead and see how can we typecast one Android object to another in Unity.\nIf you have not read the previous blogs, I would strongly recommend to read them first. You can read them on the links below.\nNative Android in Unity Native Android text sharing in Unity Native Android image sharing in Unity AndroidJavaClass is the Unity representation of a generic instance of java.lang.Class whereas AndroidJavaObject is the Unity representation of a generic instance of java.lang.Object.\nWe can create a Java class reference object using AndroidJavaClass and an object of that class using AndroidJavaObject but what if we have to typecast one Android object to another of Android class only.\nLet\u0026rsquo;s take an example where we need to get the Parcelable extra from intent in Android and typecast it to Uri object of Android itself.\nAndroid share data between activities using Parcelable. We can put anything extra which is Parcelable into the Bundle or directly into the Intent and can receive it using getParcelableExtra.\nThe Java or Kotlin equivalent code for the same will be\n//Java Code Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM); //Kotlin Code val uri = intent.getParcelableExtra\u0026lt;Parcelable\u0026gt;(Intent.EXTRA_STREAM) as Uri // or val uri = intent.getParcelableExtra\u0026lt;Uri\u0026gt;(Intent.EXTRA_STREAM) Looking at the Java code it\u0026rsquo;s easy to understand that Java directly converted it into Uri object but that is not possible in the case of Kotlin as Koltin is not a strongly typed language and the data type of the variable is decided at runtime but not at compile time.\nSame in the case of C# also. We have to typecast it to Uri manually. But since the object first received will be a Parcelable object the question is can we convert it from one object to another by just using AndroidJavaClass and AndroidJavaObject?\nThe answer is YES We can convert one object to another by just using AndroidJavaClass and AndroidJavaObject.\nWe can use java.lang.Class and its two functions forName and cast to typecast it to the desired Android/Java object.\nforName is a static function that returns the Class object associated with the class or interface with the given string name.\ncast casts the Class object to represent a subclass of the class represented by the specified class object. Checks that that the cast is valid, and throws a ClassCastException if it is not. If this method succeeds, it always returns a reference to this class object.\nThe equivalent casting code would be,\n//C# Code public AndroidJavaObject castToJavaObject(AndroidJavaObject source, string className) { var clazz = new AndroidJavaClass(\u0026#34;java.lang.Class\u0026#34;); var destClass = clazz.CallStatic\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;forName\u0026#34;, className); return destClass.Call\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;cast\u0026#34;, source); } What we have done here is, Created java.lang.Class reference object. Used its static method forName which returns the required class or interface name reference object. Used non-static method cast which ultimately casts it to the required class or interfaces reference object. And to use it for our use case, //C# code //get the context of current activity AndroidJavaObject context = unityActivity.GetStatic\u0026lt;AndroidJavaObject\u0026gt; (\u0026#34;currentActivity\u0026#34;); //get intent from the current context AndroidJavaObject intent = context.Call\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;getIntent\u0026#34;); //get parcelable extra from intent AndroidJavaObject parcelable = intent.Call\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;getParcelableExtra\u0026#34;, \u0026#34;android.intent.extra.STREAM\u0026#34;); //Cast it to Uri type AndroidJavaObject uri = \u0026lt;b\u0026gt;castToJavaObject\u0026lt;/b\u0026gt;(parcelable, \u0026#34;android.net.Uri\u0026#34;); Complete Code ","tags":["CSharp","Unity"],"title":"Typecast Android Object in Untiy"},{"categories":["Gist"],"date":"May 28, 2021","permalink":"https://agrawalsuneet.github.io/gists/typecast-android-object-in-unity/","section":"gists","summary":"This particular script will help you to typecast one Android/Java object into another in Unity.\nFor further explaination on how this works, please read the article Native Android in Unity.\n","tags":["Unity","CSharp"],"title":"Typecast Android Object in Untiy"},{"categories":["Gist"],"date":"May 21, 2021","permalink":"https://agrawalsuneet.github.io/gists/custom-android-manifest-file-in-unity/","section":"gists","summary":"This particular xml is an example of custom Android Manifest file which can be used in unity.\nFor further explaination on how this works, please read the article Custom Android Manifest File in Unity.\n","tags":["Unity"],"title":"Custom Android Manifest File in Unity"},{"categories":["Blog"],"date":"May 10, 2021","permalink":"https://agrawalsuneet.github.io/blogs/why-with-function-is-not-an-extension-to-template-class/","section":"blogs","summary":"After reading my last blog about Kotlin with function, a lot of developers have asked me about, why with is not an extension to Template class like other scope functions?\nNot only with, but run also has two implementations among which one is not an extension to Template class but a generic extension function.\nThe question is why? with is an extension to generic class means it is not specific to any class. This could have been an extension to Any class which is the base class for all the classes, similar to java.lang.Object class in Java, even if you extend it or not. Or this could have been added as an extension to Template class which is compatible with Java objects also.\nThe reason it is not an extension to Any or Template class is that we don\u0026rsquo;t want to use it for chaining purpose. with will always be the starting point of any expression but it can\u0026rsquo;t be chained to any other object or expression.\nFor chaining purpose we have let, apply, also and other scope functions but not with.\nKeep in mind that the result of with function can be chained further but the with function will never be used as chaining means it won\u0026rsquo;t be a second expression.\nclass Employee { var firstName: String = \u0026#34;\u0026#34; var age: Int = 0 } val employee: Employee = Employee() with(employee){ firstName = \u0026#34;Suneet\u0026#34; age = 27 println(firstName) } So to confirm that with can only be the starting point of any expression or it can\u0026rsquo;t be chained, with is not an extension to Any or Template class. ","tags":["Kotlin"],"title":"Why with function is not an Extension to Template class?"},{"categories":["Blog"],"date":"May 9, 2021","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-run-function/","section":"blogs","summary":"Kotlin has made our life very easy by providing features like extension functions, nullability check and much more. One such kind of really helpful feature is Scope functions. Once you understand what scope functions are, you will not able to resist yourself from using them.\nScope functions are nothing but the functions which define to the scope of the calling object. We can apply operations on that object within that scope and return the object itself from that scope function or we can even return the result of operation or operations from the scope function.\nThere are a few scope functions\nlet with run apply also To keep this article short and to the point, we will talk only about run in this article and all the use cases around it.\nrun has two variants. One is an extension function to Template class which takes a lambda (higher-order function) as a parameter, apply contract on it and ultimately return the execution of the lambda we passed as a parameter to it.\nSecond is not an extension function to Template class but a normal extension function that takes a higher-order function as parameters, applies the operations and return the lambda expression or results. The return type can also be void.\n/** * Calls the specified function [block] and returns its result. */ @kotlin.internal.InlineOnly public inline fun \u0026amp;lt;R\u0026amp;gt; run(block: () -\u0026gt; R): R { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return block() } /** * Calls the specified function [block] with `this` value as its receiver and returns its result. */ @kotlin.internal.InlineOnly public inline fun \u0026amp;lt;T, R\u0026amp;gt; T.run(block: T.() -\u0026gt; R): R { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return block() } This clarifies a few things The return type of the both run functions are nothing but the last expression we returned from our passed lambda parameters. Since its an extension function to the Template class as well as generic without any class, it can be called on any object with or without chaining. Now let\u0026rsquo;s understand what is the contract. The contract is nothing but a contract applied to the passed lambda as a parameter.\n/** * Specifies the contract of a function. * * The contract description must be at the beginning of a function and have at least one effect. * * Only the top-level functions can have a contract for now. * * @param builder the lambda where the contract of a function is described with the help of the [ContractBuilder] members. * @ContractsDsl @ExperimentalContracts @InlineOnly @SinceKotlin(\u0026#34;1.3\u0026#34;) @Suppress(\u0026#34;UNUSED_PARAMETER\u0026#34;) public inline fun contract(builder: ContractBuilder.() -\u0026gt; Unit) { } This is exactly the same contract as to any other scope function. This superimposes some conditions on the lambda we passed as a parameter to the run function. What conditions it superimposed, we need to check the parameter of the contract\nAnd what contract applied in the run functions ? /** * Specifies that the function parameter [lambda] is invoked in place. * * This contract specifies that: * 1. the function [lambda] can only be invoked during the call of the owner function, * and it won\u0026#39;t be invoked after that owner function call is completed; * 2. _(optionally)_ the function [lambda] is invoked the amount of times specified by the [kind] parameter, * see the [InvocationKind] enum for possible values. * * A function declaring the `callsInPlace` effect must be _inline_. * */ /* @sample samples.contracts.callsInPlaceAtMostOnceContract * @sample samples.contracts.callsInPlaceAtLeastOnceContract * @sample samples.contracts.callsInPlaceExactlyOnceContract * @sample samples.contracts.callsInPlaceUnknownContract */ @ContractsDsl public fun \u0026lt;R\u0026gt; callsInPlace(lambda: Function\u0026lt;R\u0026gt;, kind: InvocationKind = InvocationKind.UNKNOWN): CallsInPlace It superimposes 2 conditions\nThe lambda will be invoked only during owner function call and it won\u0026rsquo;t be called once the owner function is completed. The number of times this lambda function will be invoked (which is exactly once in our case) which is an enum. The above conditions are clear from there definition itself.\nSo basically, run function will be called only during the owner function will be called. called ONLY ONCE. called on the calling object in case of Template class extension and on the context in case of non Template class extension. and will return the expression returned by the lambda passed to the run function. Now let\u0026rsquo;s look at the use cases run which is an extension to Template class is similar to let but the only difference is in let we get a reference as it whereas in run, the reference is this.\nThe best use case of this run function is to avoid the null check. run function used with ?. ensures the execution only if the expression is non-null. You can read about the null safety in the Kotlin here\nclass Employee { var firstName: String? = null var age: Int = 0 } val employee: Employee? = Employee() employee?.firstName = \u0026#34;Suneet\u0026#34; employee?.age = 27 employee?.run { println(age) } Please note that we can even point to the calling object by this but we can\u0026rsquo;t use a named parameter in run.\nemployee?.run { println(this.age) } run function which is not an extension to Template class is similar to with but the only difference is in with we can pass the object as a param, here we can\u0026rsquo;t pass it but this will only be executed on the outer (function/class/context) scope.\nrun lets us execute a block of several statements where an expression is required.\nThis is like defining our block and the variables which will be defined in that block will not be present outside.\nval alphaNumeric = run { val digits = \u0026#34;0-9\u0026#34; val aplhabets = \u0026#34;A-Za-z\u0026#34; Regex(\u0026#34;[$digits$aplhabets]+\u0026#34;) } for (match in alphaNumeric.findAll(\u0026#34;+1234 -FFFF I-am?-a!string?!\u0026#34;)) { println(match.value) } //this will print 1234 FFFF I am a string Things to keep in mind about run, run has two variants, one is an extension function to Template class and another one is not an extension function to Template class. run uses the context as this and we can not use a named parameter instead of this. run return the last expression of the lambda passed which can also be void. ","tags":["Kotlin"],"title":"Kotlin run function"},{"categories":["Blog"],"date":"May 4, 2021","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-with-function/","section":"blogs","summary":"Kotlin has made our life very easy by providing features like extension functions, nullability check and much more. One such kind of really helpful feature is Scope functions. Once you understand what scope functions are, you will not able to resist yourself from using them.\nScope functions are nothing but the functions which define to the scope of the calling object. We can apply operations on that object within that scope and return the object itself from that scope function or we can even return the result of operation or operations from the scope function.\nThere are a few scope functions\nlet with run apply also To keep this article short and to the point, we will talk only about with in this article and all the use cases around it.\nwith is not an extension function to Template class but a normal extension function that takes a Template class object and a higher-order function as parameters, applies the operations to the passed Template class object and return the lambda expression or results. The return type can also be void.\nMore than functional, with can be used as grammatical where we can read as \u0026ldquo;with this object, do the following.\u0026rdquo;.\nWhy with is not an extension function to Template class? with is not an extension function to Template class because we don\u0026rsquo;t want to use it for chaining purpose. For chaining purpose, we have let, also and apply scope functions. with can only be the starting point of any expression. That\u0026rsquo;s the reason it\u0026rsquo;s not an extension function to the Template class.\nTo understand with function lets look at the implementation of with function first.\n/** * Calls the specified function [block] with the given [receiver] as its receiver and returns its result. */ @kotlin.internal.InlineOnly public inline fun \u0026amp;lt;T, R\u0026amp;gt; with(receiver: T, block: T.() -\u0026gt; R): R { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return receiver.block() } This clarifies a few things The return type of the with function is nothing but the last expression we returned from our passed lambda parameter. Although it\u0026rsquo;s not an extension function to Template class but we can pass any object as the first param to with function. Now let\u0026rsquo;s understand what is the contract. The contract is nothing but a contract applied to the passed lambda as a parameter.\n/** * Specifies the contract of a function. * * The contract description must be at the beginning of a function and have at least one effect. * * Only the top-level functions can have a contract for now. * * @param builder the lambda where the contract of a function is described with the help of the [ContractBuilder] members. * @ContractsDsl @ExperimentalContracts @InlineOnly @SinceKotlin(\u0026#34;1.3\u0026#34;) @Suppress(\u0026#34;UNUSED_PARAMETER\u0026#34;) public inline fun contract(builder: ContractBuilder.() -\u0026gt; Unit) { } This is exactly the same contract as to any other scope function. This superimposes some conditions on the lambda we passed as a parameter to the with function. What conditions it superimposed, we need to check the parameter of the contract\nAnd what contract applied in the with function ? /** * Specifies that the function parameter [lambda] is invoked in place. * * This contract specifies that: * 1. the function [lambda] can only be invoked during the call of the owner function, * and it won\u0026#39;t be invoked after that owner function call is completed; * 2. _(optionally)_ the function [lambda] is invoked the amount of times specified by the [kind] parameter, * see the [InvocationKind] enum for possible values. * * A function declaring the `callsInPlace` effect must be _inline_. * */ /* @sample samples.contracts.callsInPlaceAtMostOnceContract * @sample samples.contracts.callsInPlaceAtLeastOnceContract * @sample samples.contracts.callsInPlaceExactlyOnceContract * @sample samples.contracts.callsInPlaceUnknownContract */ @ContractsDsl public fun \u0026lt;R\u0026gt; callsInPlace(lambda: Function\u0026lt;R\u0026gt;, kind: InvocationKind = InvocationKind.UNKNOWN): CallsInPlace It superimposes 2 conditions\nThe lambda will be invoked only during owner function call and it won\u0026rsquo;t be called once the owner function is completed. The number of times this lambda function will be invoked (which is exactly once in our case) which is an enum. The above conditions are clear from there definition itself.\nSo basically, with function will be\ncalled only during the owner function will be called. called ONLY ONCE. called on the calling object. and will return the expression returned by the lambda passed to the with function. Now let\u0026rsquo;s look at the use cases\nwith is used to call the function on the context object without providing the lambda result.\nThis means with can\u0026rsquo;t be chained or we can\u0026rsquo;t pass any lambda result to with function. with will always be the starting point of any expression.\nclass Employee { var firstName: String = \u0026#34;\u0026#34; var age: Int = 0 } val employee: Employee = Employee() with(employee){ firstName = \u0026#34;Suneet\u0026#34; age = 27 println(firstName) } Please note that we can even point to the calling object by this but we can\u0026rsquo;t use a named parameter in apply.\nval employee: Employee = Employee() with(employee){ this.firstName = \u0026#34;Suneet\u0026#34; this.age = 27 println(this.firstName) } We can avoid the use of this pointer or use it to avoid the conflicts between other properties or objects with the same name within that class. It points to the calling object only.\nwe can return the last expression from the higher-order function passed to the with function.\nval details = with(employee){ this.firstName = \u0026#34;Suneet\u0026#34; this.age = 27 \u0026#34;The name of the employee is $firstName and age is $age\u0026#34; } println(details) We can even chain the with function\nval list = listOf(1, 2, 3, 4, 5) with(list){ list.filter { it % 2 == 0 } } .forEach { println(it) } Things to keep in mind about with, with is not an extension function to Template class. with uses the context as this and we can not use a named parameter instead of this. with return the last expression of the lambda passed which can also be void. ","tags":["Kotlin"],"title":"Kotlin with function"},{"categories":["Blog"],"date":"April 29, 2021","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-also-function/","section":"blogs","summary":"In continuation to my previous post where I explained about Kotlin let function and Kotlin apply function, let\u0026rsquo;s try to understand today about also function today.\nJust to recap, Scope functions are nothing but the functions which define to the scope of the calling object. We can apply operations on that object within that scope and return the object itself from that scope function or we can even return the result of operation or operations from the scope function.\nThere are a few scope functions\nlet with run apply also To keep this article short and to the point, we will talk only about also in this article and all the use cases around it.\nalso is used to perform some actions on the object and returns the object itself. A reference to the calling object is available inside the also function instead of the context (this).\nMore than functional, also can be used as grammatical where we can read as \u0026ldquo;also do the following with the object\u0026rdquo;.\nTo understand also function lets look at the implementation of also function first.\n/** * Calls the specified function [block] * with `this` value as its argument * and returns `this` value. */ @kotlin.internal.InlineOnly @SinceKotlin(\u0026#34;1.1\u0026#34;) public inline fun \u0026lt;T\u0026gt; T.also(block: (T) -\u0026gt; Unit): T { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } block(this) return this } also is an extension function to Template class which takes a lambda as a parameter, apply contract on it, execute the lambda function within the scope of calling object and ultimately return the same calling object of Template class itself.\nThis clarifies a few things The return type of the also function is nothing but the same calling object. Since its an extension function to the Template class, it can be called on any object. Now let\u0026rsquo;s understand what is the contract. The contract is nothing but a contract applied to the passed lambda as a parameter.\n/** * Specifies the contract of a function. * * The contract description must be at the beginning of a function and have at least one effect. * * Only the top-level functions can have a contract for now. * * @param builder the lambda where the contract of a function is described with the help of the [ContractBuilder] members. * @ContractsDsl @ExperimentalContracts @InlineOnly @SinceKotlin(\u0026#34;1.3\u0026#34;) @Suppress(\u0026#34;UNUSED_PARAMETER\u0026#34;) public inline fun contract(builder: ContractBuilder.() -\u0026gt; Unit) { } This is exactly the same contract as to any other scope function. This superimposes some conditions on the lambda we passed as a parameter to the also function. What conditions it superimposed, we need to check the parameter of the contract\nAnd what contract applied in the also function ? /** * Specifies that the function parameter [lambda] is invoked in place. * * This contract specifies that: * 1. the function [lambda] can only be invoked during the call of the owner function, * and it won\u0026#39;t be invoked after that owner function call is completed; * 2. _(optionally)_ the function [lambda] is invoked the amount of times specified by the [kind] parameter, * see the [InvocationKind] enum for possible values. * * A function declaring the `callsInPlace` effect must be _inline_. * */ /* @sample samples.contracts.callsInPlaceAtMostOnceContract * @sample samples.contracts.callsInPlaceAtLeastOnceContract * @sample samples.contracts.callsInPlaceExactlyOnceContract * @sample samples.contracts.callsInPlaceUnknownContract */ @ContractsDsl public fun \u0026lt;R\u0026gt; callsInPlace(lambda: Function\u0026lt;R\u0026gt;, kind: InvocationKind = InvocationKind.UNKNOWN): CallsInPlace It superimposes 2 conditions\nThe lambda will be invoked only during owner function call and it won\u0026rsquo;t be called once the owner function is completed. The number of times this lambda function will be invoked (which is exactly once in our case) which is an enum. The above conditions are clear from there definition itself.\nSo basically, also function will be called only during the owner function will be called. called ONLY ONCE. called on the calling object. and will return the object itself on which the also function is called. Now let\u0026rsquo;s look at the use cases also is used to perform actions on the object that take the context object as an argument.\nclass ConnectionManager { var endPoint: String = \u0026#34;\u0026#34; var credentials: Pair\u0026lt;String, String\u0026gt; = Pair(\u0026#34;\u0026#34;, \u0026#34;\u0026#34;) fun connect() { //make network connection } } val connectionManager = ConnectionManager() .apply { endPoint = \u0026#34;http://endpoint.com\u0026#34; credentials = Pair(\u0026#34;username\u0026#34;, \u0026#34;password\u0026#34;) } .also { it.connect() } it can also be used for chaining as also returns this context only.\nval connectionManager = ConnectionManager() .apply { endPoint = \u0026#34;http://endpoint.com\u0026#34; credentials = Pair(\u0026#34;username\u0026#34;, \u0026#34;password\u0026#34;) } .also { it.connect() } .also { print(\u0026#34;connection is made on ${it.endPoint}\u0026#34;) } we can even use a named parameter in also.\nval connectionManager = ConnectionManager() .apply { endPoint = \u0026#34;http://endpoint.com\u0026#34; credentials = Pair(\u0026#34;username\u0026#34;, \u0026#34;password\u0026#34;) } .also { manager -\u0026gt; manager.connect() } Since there is no this context passed inside also function, it doesn\u0026rsquo;t shadow the this context from the outer scope.\nThings to keep in mind about also, also uses the context as it or we can use a named parameter. also returns the calling object itself. ","tags":["Kotlin"],"title":"Kotlin also function"},{"categories":["Blog"],"date":"April 23, 2021","permalink":"https://agrawalsuneet.github.io/blogs/why-map-does-not-extend-collection-interface/","section":"blogs","summary":"Collections in any language is an interface that stores similar data type objects and provides an iteration functionality. The common extensions of Collection are List and Set.\nThe Map is a well-known data structure used to store key-value pairs where keys will be unique.\nWe can take a reference of any language but let\u0026rsquo;s look at the example of Java for reference as Collection Framework from Java is very popular.\nJava has Iterable interface which is extended by Collection. The Collection is further extended by List, Queue and Set which has their different-different implementations but the unique thing notice is that the Map interface doesn\u0026rsquo;t extend Collection interface.\nWhy Map does not extend Collection interface? Because they are of an incompatible type.\nList, Set and Queue are a collection of similar kind of objects but just values where a Map is a collection of key and value pairs. List Set and Queue have add as a function which takes a value as param to add an element whereas Map has put as a function which takes a key and a value as params to add a key-value pair. List, Set and Queue provide iterate functionality over the value whereas Maps has keys to iterate over which is ultimately a Set and Values as Collection. public interface Map\u0026lt;K,V\u0026gt; { ... Set\u0026lt;K\u0026gt;; keySet(); Collection\u0026lt;V\u0026gt; values(); ... } ","tags":["Programming-Basics"],"title":"Why Map does not extend Collection interface?"},{"categories":["Blog"],"date":"April 20, 2021","permalink":"https://agrawalsuneet.github.io/blogs/any-none-all-kotlin/","section":"blogs","summary":"Kotlin is a powerful language that reduces a lot of boilerplate code required to perform basic operations in comparison to Java. The classic examples for the same are any, non and all functions which were added to the Iterable interface and Map interface.\nLet try to understand what do they do, why they are required and when to use them. But before we begin, I am assuming a basic knowledge of Map, Set and List.\nAny Set or List implementation implements Collection interface (indirectly) which extends Iterable and any Map implementation implement Map interface. All three of them are used to store similar data types with different benefits among the three.\nThe List provides the functionality to maintain the ordered collection. whereas Set and Map don\u0026rsquo;t provide the ordering. Both of them provides uniqueness but Map is a key-value pair mapping.\nIn short, all three of them are used to store data/objects of similar types.\nSince the collection is involved, filtering will be required to iterate the data faster. To make this filter easier, Kotlin has added a few functions as an extension function to Iterable as well as Map.\nLet look at them one by one.\nAny Any is a function that is added as an extension to Iterable and Map interfaces, which take a higher-order function as param to predicate the condition and return Boolean as true, if any of the items in List, Set or Map confirms that condition, else return false.\nval list = listOf(\u0026#34;one\u0026#34;, \u0026#34;two\u0026#34;, \u0026#34;three\u0026#34;, \u0026#34;four\u0026#34;) val set = setOf(\u0026#34;one\u0026#34;, \u0026#34;two\u0026#34;, \u0026#34;three\u0026#34;, \u0026#34;four\u0026#34;) val map = mapOf(1 to \u0026#34;one\u0026#34;, 2 to \u0026#34;two\u0026#34;, 3 to \u0026#34;three\u0026#34;, 4 to \u0026#34;four\u0026#34;) println(list.any { it.endsWith(\u0026#34;e\u0026#34;) }) // true println(set.any { it.endsWith(\u0026#34;e\u0026#34;) }) // true println(map.any { it.value.endsWith(\u0026#34;e\u0026#34;) }) // true Let\u0026rsquo;s look at the extension function any, defined in Kotlin\n/** * Returns `true` if at least one element matches the given [predicate]. * * @sample samples.collections.Collections.Aggregates.anyWithPredicate */ public inline fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.any(predicate: (T) -\u0026gt; Boolean): Boolean { if (this is Collection \u0026amp;\u0026amp; isEmpty()) return false for (element in this) if (predicate(element)) return true return false } /** * Returns `true` if at least one entry matches the given [predicate]. * * @sample samples.collections.Collections.Aggregates.anyWithPredicate */ public inline fun \u0026lt;K, V\u0026gt; Map\u0026lt;out K, V\u0026gt;.any(predicate: (Map.Entry\u0026lt;K, V\u0026gt;) -\u0026gt; Boolean): Boolean { if (isEmpty()) return false for (element in this) if (predicate(element)) return true return false } None Similar to Any, None is a function that is added as an extension to Iterable and Map interfaces, which also takes a higher-order function as param to predicate the condition and return Boolean as true if none of the items in List, Set or Map confirms that condition, else return false.\nval list = listOf(\u0026#34;one\u0026#34;, \u0026#34;two\u0026#34;, \u0026#34;three\u0026#34;, \u0026#34;four\u0026#34;) val set = setOf(\u0026#34;one\u0026#34;, \u0026#34;two\u0026#34;, \u0026#34;three\u0026#34;, \u0026#34;four\u0026#34;) val map = mapOf(1 to \u0026#34;one\u0026#34;, 2 to \u0026#34;two\u0026#34;, 3 to \u0026#34;three\u0026#34;, 4 to \u0026#34;four\u0026#34;) println(list.none { it.endsWith(\u0026#34;e\u0026#34;) }) //false println(set.none { it.endsWith(\u0026#34;e\u0026#34;) }) //false println(map.none { it.value.endsWith(\u0026#34;e\u0026#34;) }) //false Let\u0026rsquo;s look at the extension function none, defined in Kotlin\n/** * Returns `true` if no elements match the given [predicate]. * * @sample samples.collections.Collections.Aggregates.noneWithPredicate */ public inline fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.none(predicate: (T) -\u0026gt; Boolean): Boolean { if (this is Collection \u0026amp;\u0026amp; isEmpty()) return true for (element in this) if (predicate(element)) return false return true } /** * Returns `true` if no entries match the given [predicate]. * * @sample samples.collections.Collections.Aggregates.noneWithPredicate */ public inline fun \u0026lt;K, V\u0026gt; Map\u0026lt;out K, V\u0026gt;.none(predicate: (Map.Entry\u0026lt;K, V\u0026gt;) -\u0026gt; Boolean): Boolean { if (isEmpty()) return true for (element in this) if (predicate(element)) return false return true } All Similar to Any and None, All is a function that is added as an extension to Iterable and Map interfaces, which also takes a higher-order function as param to predicate the condition and return Boolean as true if all of the items in List, Set or Map confirms that condition, else return false.\nval list = listOf(\u0026#34;one\u0026#34;, \u0026#34;two\u0026#34;, \u0026#34;three\u0026#34;, \u0026#34;four\u0026#34;) val set = setOf(\u0026#34;one\u0026#34;, \u0026#34;two\u0026#34;, \u0026#34;three\u0026#34;, \u0026#34;four\u0026#34;) val map = mapOf(1 to \u0026#34;one\u0026#34;, 2 to \u0026#34;two\u0026#34;, 3 to \u0026#34;three\u0026#34;, 4 to \u0026#34;four\u0026#34;) println(list.all { it.endsWith(\u0026#34;e\u0026#34;) }) //false println(set.all { it.endsWith(\u0026#34;e\u0026#34;) }) //false println(map.all { it.value.endsWith(\u0026#34;e\u0026#34;) }) //false Let\u0026rsquo;s look at the extension function all, defined in Kotlin\n/** * Returns `true` if all elements match the given [predicate]. * * @sample samples.collections.Collections.Aggregates.all */ public inline fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.all(predicate: (T) -\u0026gt; Boolean): Boolean { if (this is Collection \u0026amp;\u0026amp; isEmpty()) return true for (element in this) if (!predicate(element)) return false return true } /** * Returns `true` if all entries match the given [predicate]. * * @sample samples.collections.Collections.Aggregates.all */ public inline fun \u0026lt;K, V\u0026gt; Map\u0026lt;out K, V\u0026gt;.all(predicate: (Map.Entry\u0026lt;K, V\u0026gt;) -\u0026gt; Boolean): Boolean { if (isEmpty()) return true for (element in this) if (!predicate(element)) return false return true } Any and None without any params Any and None functions also have an overload to both Iterable and Map interfaces which don\u0026rsquo;t take any param but just check if the collection is empty or not.\nAny returns true if the collection is not empty whereas None return true if the collection is empty.\nval list = listOf(\u0026#34;one\u0026#34;, \u0026#34;two\u0026#34;, \u0026#34;three\u0026#34;, \u0026#34;four\u0026#34;) val set = setOf(\u0026#34;one\u0026#34;, \u0026#34;two\u0026#34;, \u0026#34;three\u0026#34;, \u0026#34;four\u0026#34;) val map = mapOf(1 to \u0026#34;one\u0026#34;, 2 to \u0026#34;two\u0026#34;, 3 to \u0026#34;three\u0026#34;, 4 to \u0026#34;four\u0026#34;) println(list.any()) //true println(set.any()) //true println(map.any()) //true println(list.none()) //false println(set.none()) //false println(map.none()) //false Let\u0026rsquo;s look at the extension functions, defined in Kotlin\n/** * Returns `true` if collection has at least one element. * * @sample samples.collections.Collections.Aggregates.any */ public fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.any(): Boolean { if (this is Collection) return !isEmpty() return iterator().hasNext() } /** * Returns `true` if map has at least one entry. * * @sample samples.collections.Collections.Aggregates.any */ public fun \u0026lt;K, V\u0026gt; Map\u0026lt;out K, V\u0026gt;.any(): Boolean { return !isEmpty() } /** * Returns `true` if the collection has no elements. * * @sample samples.collections.Collections.Aggregates.none */ public fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.none(): Boolean { if (this is Collection) return isEmpty() return !iterator().hasNext() } /** * Returns `true` if the map has no entries. * * @sample samples.collections.Collections.Aggregates.none */ public fun \u0026lt;K, V\u0026gt; Map\u0026lt;out K, V\u0026gt;.none(): Boolean { return isEmpty() } Benefits of using these functions There is no difference in the implementation but since these are inbuild inline function, you don’t have to write the entire iteration and condition check on your own. Please note that there is no difference in time or space complexity also.\nThe only reason I wrote about this as a blog is because I feel I am lazy and prefers to use all inbuild functions to write fewer lines of code. :) These were a few of them.\n","tags":["Kotlin"],"title":"any(), none() \u0026 all() : Kotlin"},{"categories":["Blog"],"date":"April 16, 2021","permalink":"https://agrawalsuneet.github.io/blogs/if-vs-if-let-vs-guard-let-in-swift/","section":"blogs","summary":"if let and guard let are two conditional operators or condition checker which make our life super easy. Other languages have only if as condition checker but swift provides if let as well as guard let also which are operationally same but a bit different in functionality.\nTo understand their differences, let\u0026rsquo;s try to understand what they are in details first.\nif condition Normal if condition is nothing but to check whether a condition is true or not.\nlet colors = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] if colors.contains(\u0026#34;red\u0026#34;) { print(\u0026#34;red is present in palette\u0026#34;) } This can be clubbed with else and else if but both of them are optional.\nlet colors = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] if colors.contains(\u0026#34;red\u0026#34;) { print(\u0026#34;red is present in palette\u0026#34;) } else { print(\u0026#34;red is not present in palette\u0026#34;) } we can even club multiple if conditions with simple \u0026amp;\u0026amp; or || operators based on the use case.\nlet colors = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] if colors.contains(\u0026#34;red\u0026#34;) || colors.contains(\u0026#34;green\u0026#34;) { print(\u0026#34;red or green are present in palette\u0026#34;) } else { print(\u0026#34;red and green both are not present in palette\u0026#34;) } if let Now let\u0026rsquo;s think about someplace where we want to compute something and based on the computed value we need to put an if condition.\nlet colors = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] let index = colors.firstIndex(where: {$0.elementsEqual(\u0026#34;green\u0026#34;)}) if index != nil { print(\u0026#34;green is present in palette at position \\(index ?? -1)\u0026#34;) } else { print(\u0026#34;green is not present in palette\u0026#34;) } We are trying to check if an element is present in an array and if present we are trying to print its position.\nThe same code can be replaced with if let instead of if condition.\nlet colors = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] if let index = colors.firstIndex(where: {$0.elementsEqual(\u0026#34;green\u0026#34;)}) { print(\u0026#34;green is present in palette at position \\(index)\u0026#34;) } else { print(\u0026#34;green is not present in palette\u0026#34;) } We combined the computation and evaluation within a single statement by using if let.\nThe thing to notice here is that the variable index is not nullable in if let whereas it was a nullable variable in if condition. We can club multiple if let also within the same condition check by spearating them using comma ,\nlet colors : [String] = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] if let redIndex = colors.firstIndex(where: {$0.elementsEqual(\u0026#34;red\u0026#34;)}), let greenIndex = colors.firstIndex(where: {$0.elementsEqual(\u0026#34;green\u0026#34;)}) { print(\u0026#34;red is present in palette at position \\(redIndex) and green is present in palette at position \\(greenIndex)\u0026#34;) } else { print(\u0026#34;\\(red) and \\(green) are not present in palette\u0026#34;) } Or we can even check the nullability and assign it to another variable that will be non-nullable. This is called optional unwrapping.\nlet colors : [String]? = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] let nullableGreen : String? = \u0026#34;green\u0026#34; if let green = nullableGreen, let index = colors?.firstIndex(where: {$0.elementsEqual(green)}) { print(\u0026#34;\\(green) is present in palette at position \\(index)\u0026#34;) } else { print(\u0026#34;\\(nullableGreen ?? \u0026#34;undefined\u0026#34;) is not present in palette\u0026#34;) } The thing to notice here is that the variable green is only accessible only in if let but not in the else scope. It\u0026rsquo;s not event available after the if else scope. let colors : [String]? = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] let nullableGreen : String? = \u0026#34;green\u0026#34; if let green = nullableGreen, let index = colors?.firstIndex(where: {$0.elementsEqual(green)}) { print(\u0026#34;\\(green) is present in palette at position \\(index)\u0026#34;) } else { print(\u0026#34;\\(nullableGreen ?? \u0026#34;undefined\u0026#34;) is not present in palette\u0026#34;) } print(green) \u0026lt;e\u0026gt;//Compile type error: cannot find \u0026#39;green\u0026#39; in scope\u0026lt;/e\u0026gt; guard let guard let can also be used for condition check and it can also unwrap the optional values but it works a bit different from if let.\nguard let is designed to exit the current function, loop, or condition if the check fails. func checkColorInPalette() { let colors : [String] = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] guard let index = colors.firstIndex(where: {$0.elementsEqual(\u0026#34;green\u0026#34;)}) else { print(\u0026#34;green is not present in palette\u0026#34;) return } print(print(\u0026#34;green is present in palette at position \\(index)\u0026#34;)) } Similar to if let, guard let can also be clubbed with multiple let conditions using comma , and it can also be used for optional unwrapping.\nfunc checkColorInPalette() { let colors : [String] = [\u0026#34;red\u0026#34;, \u0026#34;green\u0026#34;, \u0026#34;blue\u0026#34;] let nullableGreen : String? = \u0026#34;green\u0026#34; guard let green = nullableGreen, let index = colors.firstIndex(where: {$0.elementsEqual(green)}) else { print(\u0026#34;green is not present in palette\u0026#34;) return } print(print(\u0026#34;\\(green) is present in palette at position \\(index)\u0026#34;)) } The important thing to notice here is that the let variables defined in guard statements are also accessible after the statement but they are inaccessible inside the else condition.\nDifference between if and if let/guard let if is just a conditional checker whereas if let and guard let can define variables also where we can do computation. We can club multiple conditions or expression in all three. Only if let or guard let can do the optional unwrapping. Difference between if let and guard let if let is similar to if condition with the additional functionality of defining let variable where we can do the computation or optional unwrapping. guard let is also similar to if let but it focus on the \u0026ldquo;happy path\u0026rdquo; means if the condition is not true, code will not execute further in that particular function, loop or condition but it will return, break or throw. In if let, the defined let variables are available within the scope of that if condition but not in else condition or even below that. In guard let, the defined let variables are not available in the else condition but after that, it\u0026rsquo;s available throughout till the function ends or anything.\n","tags":["Swift"],"title":"if vs if let vs guard let in Swift"},{"categories":["Blog"],"date":"April 13, 2021","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-single-expression-function/","section":"blogs","summary":"Kotlin is a powerful language that reduced a lot of boilerplate code when compared to Java. The single expression function is the same in terms of reducing the boilerplate code.\nThe single expression function, as his name suggests, is the function that just has a single expression. We can remove the return type of that function, braces as well as return keyword from it.\nThink about a function that has some calculation to be done based on the passed argument and return the result.\nfun convertToFahrenheit(degree : Float) : Float { return (degree * 9 / 5) + 32 } println(convertToFahrenheit(degree = 11f)) This can be replaced as\nfun convertToFahrenheit(degree : Float) = (degree * 9 / 5) + 32 println(convertToFahrenheit(degree = 11f)) There can be another function that has no param passed and just returns something, but that can be replaced with a variable also with or without overriding getter so there is no point.\nStill, that function will be called as single expression function.\nval name : String = \u0026#34;John\u0026#34; fun getName() = \u0026#34;John\u0026#34; Single expression function can be used with any idioms like if-else, when, nullable, operations on the List, Map or almost everything.\nif-else fun getResult(percentage : Int) = if (percentage \u0026gt; 40) \u0026#34;Pass\u0026#34; else \u0026#34;Fail\u0026#34; println(getResult(percentage = 60)) when expression fun getBaseColorCode(color: String) = when (color) { \u0026#34;Red\u0026#34; -\u0026gt; 0xff0000 \u0026#34;Green\u0026#34; -\u0026gt; 0x00ff00 \u0026#34;Blue\u0026#34; -\u0026gt; 0x0000ff else -\u0026gt; throw IllegalArgumentException(\u0026#34;Invalid base color\u0026#34;) } println(getBaseColorCode(color = \u0026#34;Red\u0026#34;)) Collection and its operations fun getList(divisibleBy : Int) = listOf(1, 2, 3, 4, 5) .filter{ it -\u0026gt; it%divisibleBy == 0 } println(getList(divisibleBy = 2)) These are helpfully when need to add small helper functions.\n","tags":["Kotlin"],"title":"Kotlin : Single Expression Function"},{"categories":["Blog"],"date":"March 6, 2021","permalink":"https://agrawalsuneet.github.io/blogs/reified-kotlin/","section":"blogs","summary":"Before we learn about reified, Generics in any language is the powerful features that allow us to define classes, methods and properties which are accessible using different data types while keeping a check of the compile-time type safety.\nThe best example for a generics is Array or any List/Collection implementation.\npackage kotlin /** * Represents an array (specifically, a Java array when targeting the JVM platform). * Array instances can be created using the [arrayOf], [arrayOfNulls] and [emptyArray] * standard library functions. * See [Kotlin language documentation](https://kotlinlang.org/docs/reference/basic-types.html#arrays) * for more information on arrays. */ public class Array\u0026lt;T\u0026gt; { /** * Creates a new array with the specified [size], where each element is calculated by calling the specified * [init] function. * * The function [init] is called for each array element sequentially starting from the first one. * It should return the value for an array element given its index. */ public inline constructor(size: Int, init: (Int) -\u0026gt; T) /** * Returns the array element at the specified [index]. This method can be called using the * index operator. * ``` * value = arr[index] * ``` * * If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException] except in Kotlin/JS * where the behavior is unspecified. */ public operator fun get(index: Int): T /** * Sets the array element at the specified [index] to the specified [value]. This method can * be called using the index operator. * ``` * arr[index] = value * ``` * * If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException] except in Kotlin/JS * where the behavior is unspecified. */ public operator fun set(index: Int, value: T): Unit /** * Returns the number of elements in the array. */ public val size: Int /** * Creates an iterator for iterating over the elements of the array. */ public operator fun iterator(): Iterator\u0026lt;T\u0026gt; } Here the templete T can be of any class that the reason we can create an Array or List of any class objects.\nNow, let\u0026rsquo;s try to get the type of this template at run time within the function.\nfun \u0026lt;T\u0026gt; Array\u0026lt;T\u0026gt;.average() : Float { print(\u0026#34;${T::class.java}\u0026#34;) \u0026lt;e\u0026gt;//Compilation Error\u0026lt;/e\u0026gt; //return default value return 0.0f } What we are trying to achieve here is we want to add an extension function to Array which will check the type at run time and if that type is Int, it will return the average of all the elements in that array else this will return 0.0f\nThis will give the below compilation error\nCannot use \u0026#39;T\u0026#39; as reified type parameter. Use a class instead. The possible way to access the type of the Template class is by passing it as a parameter.\nSince we can not use the type of template at runtime directly, we need to use reified here.\nReified To get the information about the type of Template class, we will have to use a keyword called reified in Kotlin. Also, in order to use the reified type, we need to mark the function as inline.\ninline fun \u0026lt;reified T\u0026gt; Array\u0026lt;T\u0026gt;.average() : Float { print(\u0026#34;${T::class.java}\u0026#34;) //return default value return 0.0f } Lets try to understand what is happening exactly using byte code for the same example\npublic static final float average(@NotNull Object[] $this$average) { int $i$f$average = 0; //this variable is not used anywhere Intrinsics.checkParameterIsNotNull($this$average, \u0026#34;$this$average\u0026#34;); Intrinsics.reifiedOperationMarker(4, \u0026#34;T\u0026#34;); String var2 = String.valueOf(Object.class); boolean var3 = false; //this variable is not used anywhere System.out.print(var2); //return default value return 0.0F; } Since, we have used extenstion function, we can see Object class but when we actually use it and check its bype code,\n//Kotlin code var arr = arrayOf(1, 2, 3, 4, 5) var average = arr.average() //Java ByteCode Integer[] arr = new Integer[]{1, 2, 3, 4, 5}; int $i$f$average = false; //this variable is not used anywhere String var4 = String.valueOf(Integer.class); boolean var5 = false; //this variable is not used anywhere System.out.print(var4); float average = 0.0F; As its an inline function, the implementation will be copied at every calling place.\nWe can cleary see in the bytecode that the compiler copied the type ie Integer in our case at the calling place and then printed the class of it. The bolier plate code of checking the type and copying it at the calling place was taken care by compiler itself and we got the exact same type in the compiled code.\nIn order to achieve the average calculation functionality in the case of Integers array, we can use the below function.\ninline fun \u0026lt;reified T\u0026gt; Array\u0026lt;T\u0026gt;.average() : Float { if (T::class.java == Integer::class.java){ var sum = 0 for (item in this){ if (item is Int) { sum += item } } return (sum / this.size).toFloat() } //return default value return 0.0f } Same function with different return types Think of a situation where you want to return different data types or class objects from same function.\nWe can\u0026rsquo;t use method overloading as overloading only works with different number of params or different data types of params.\nIn this situation also, reified will be really useful.\ninline fun \u0026lt;reified T\u0026gt; displayAmountAsText(amount: Int): T { return when (T::class) { Int::class -\u0026gt; amount as T String::class -\u0026gt; \u0026#34;$amount USD left in your account\u0026#34; as T else -\u0026gt; \u0026#34;Please enter valid type\u0026#34; as T } } The only difference in using reified for return type is we need to explicitly define the data type while using the function else the compiler will throw a compile-time error.\nvar amountInDouble : Int = displayAmountAsText(10) println(amountInDouble) var amountInString : String = displayAmountAsText(10) println(amountInString) ","tags":["Kotlin"],"title":"Reified : Kotlin"},{"categories":["Blog"],"date":"December 16, 2020","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-enum-classes/","section":"blogs","summary":"Enums are special classes which limit the possible values of an object for that class. The possible values defined for that class are final or unchangeable.\nThe easiest way to define an enum is\nenum class Direction { EAST, WEST, NORTH, SOUTH } Here each enum constant is an object.\nFor using these values\nvar direction : Direction = Direction.EAST Base class of all Enum Classes There is a base class for all enum classes which is defined in kotlin package.\n/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package kotlin /** * The common base class of all enum classes. * See the [Kotlin language documentation](https://kotlinlang.org/docs/reference/enum-classes.html) for more * information on enum classes. */ public abstract class Enum\u0026lt;E : Enum\u0026lt;E\u0026gt;\u0026amp;gt(name: String, ordinal: Int): Comparable\u0026lt;E\u0026amp;gt { companion object {} /** * Returns the name of this enum constant, exactly as declared in its enum declaration. */ public final val name: String /** * Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant * is assigned an ordinal of zero). */ public final val ordinal: Int public override final fun compareTo(other: E): Int /** * Throws an exception since enum constants cannot be cloned. * This method prevents enum classes from inheriting from `Cloneable`. */ protected final fun clone(): Any public override final fun equals(other: Any?): Boolean public override final fun hashCode(): Int public override fun toString(): String /** * Returns an array containing the constants of this enum type, in the order they\u0026#39;re declared. * This method may be used to iterate over the constants. * @values */ /** * Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.) * @throws IllegalArgumentException if this enum type has no constant with the specified name * @valueOf */ } Name and Ordinal These two properties are available by default for each enum constant as these are added in the base class itself.\nName is the actual name by which the enum constant is defined whereas ordinal is the sequence of that particular enum constant in the enum class having the first one starting from 0\nval direction = Direction.NORTH println(direction.name) println(direction.ordinal) // this will print NORTH 2 Method overriding in Enum As you can see in the base class, all functions are final and cannot be overridden except toString. we can override toString function for any or all object in that enum.\nIt is not compulsory to override for all. we can override for just one also.\nenum class Direction { EAST { override fun toString(): String { return \u0026#34;East direction\u0026#34; } }, WEST { override fun toString(): String { return \u0026#34;West direction\u0026#34; } }, NORTH { override fun toString(): String { return \u0026#34;North direction\u0026#34; } }, SOUTH { override fun toString(): String { return \u0026#34;South direction\u0026#34; } } } Variables in Enum class Similar to any other class, we can have other variables also with each enum constant.\nenum class Direction(val dirCode: Int) { EAST(1), WEST(2), NORTH(3), SOUTH(4) } val direction = Direction.WEST println(direction.dirCode) //this will print 2 You can even modify the variable according to the needs by declaring that variables as mutable or var\nenum class Direction(var dirCode: Int) { EAST(1), WEST(2), NORTH(3), SOUTH(4) } val direction = Direction.WEST Direction.WEST.dirCode = 10 println(direction.dirCode) //this will print 10 Functions in Enum classes Since all enum constants are objects and enum is a class, we can define any number of functions in the enum class or even can define an abstract function in enum class which will be implemented by the Enum objects.\nenum class Direction(var dirCode: Int) { EAST(1) { override fun humanDirection(): String { return \u0026#34;to Right side\u0026#34; } }, WEST(2) { override fun humanDirection(): String { return \u0026#34;to left side\u0026#34; } }, NORTH(3) { override fun humanDirection(): String { return \u0026#34;to up side\u0026#34; } }, SOUTH(4) { override fun humanDirection(): String { return \u0026#34;to down side\u0026#34; } }; abstract fun humanDirection(): String fun doSomethingWithDirection(){ println(this.dirCode * 10) } } val direction = Direction.EAST direction.doSomethingWithDirection() direction.humanDirection() Interface implementation in Enum class We can even define an interface and can implement it in any enum class. There are two ways an enum class can implement an interface. Either all the objects of that enum override the interface methods or the methods were implemented on the class level means common for all.\ninterface IDirection { fun humanDirection(): String } interface Instructions { fun generalDirections() } enum class Direction : IDirection, Instructions { EAST { override fun humanDirection(): String { return \u0026#34;to Right side\u0026#34; } }, WEST { override fun humanDirection(): String { return \u0026#34;to left side\u0026#34; } }, NORTH { override fun humanDirection(): String { return \u0026#34;to up side\u0026#34; } }, SOUTH { override fun humanDirection(): String { return \u0026#34;to down side\u0026#34; } }; override fun generalDirections() { println(\u0026#34;take and map and compare directions\u0026#34;) } } val direction = Direction.EAST direction.humanDirection() direction.generalDirections() Enum Constants (valueOf) To convert a string value into an enum object, we can use valueOf function which will return us the enum constant by its name.\nenum class Direction { EAST, WEST, NORTH, SOUTH } val dir = Direction.valueOf(\u0026#34;WEST\u0026#34;) println(dir.name) //this will print //WEST We can even use a generic function which takes a type of input.\nval dir = enumValueOf\u0026lt;Direction\u0026gt;(\u0026#34;NORTH\u0026#34;) println(dir.name) //this will print //NORTH Keep in mind that the above functions take the value which is case sensitive and throws an IllegalArgumentException if the specified name does not match with any of the enum constants defined in the class.\nEnum Values To get all the possible values in an array, we can use values or enumValues function which will return us an array of all the values in that enum class.\nval allValues = Direction.values() allValues.forEach{ println(it.name) } val allEnumValues = enumValues\u0026lt;Direction\u0026gt;() allEnumValues.forEach{ println(it.name) } Comparable in Enum class Enum classes also implement Comparable interface which has compareTo method. It compares the position or ordinal in enum and returns the difference either in positive or negative integer or zero if equal.\nval east = Direction.EAST val north = Direction.NORTH println(east.compareTo(north)) //this will print //-2 println(north.compareTo(east)) //this will print //2 ","tags":["Kotlin"],"title":"Kotlin Enum Classes"},{"categories":["Blog"],"date":"December 14, 2020","permalink":"https://agrawalsuneet.github.io/blogs/uiview-clicklistener-swift/","section":"blogs","summary":"Adding a click event to a UIView is something that is required most of the time. For views like UIButton, we can connect an IBAction with the event type and detect the click events but sometimes we need it for Lable or even other views.\nIf you try to add an IBAction to your view, you won\u0026rsquo;t get Action as an option while connecting it with ViewController.\nThe only possible way to add a click event on UIView is using UITapGestureRecognizer. You can either add an UITapGestureRecognizer using interface builder or you can do it programmatically.\n/swift code in view controller let gesture = UITapGestureRecognizer(target: self, action: #selector(self.clickAction(sender:))) self.myView.addGestureRecognizer(gesture) func clickAction(sender : UITapGestureRecognizer) { // Do what you want } This way is a bit inefficient as we need to add one function for each view which will be clickable.\nThere is a better way where we can add this functionality to each view without making our class messy.\nWe can add this to the UIView extension itself which will be a very clean approach and will make our life super easy.\nFirst, extend UITapGestureRecognizer and add a property to it which holds a function which takes 0 params and is of Void return type.\nclass ClickListener: UITapGestureRecognizer { var onClick : (() -\u0026gt; Void)? = nil } Now create an extension to UIView class and add a method which takes an escaping type of variable which is the reference to a function which need to be run if the view clicked.\nCreate our ClickListener class object and add a selector to it. Add the passed argument to this ClickListener and add the gesture object to the view.\nextension UIView { func setOnClickListener(action :@escaping () -\u0026gt; Void){ let tapRecogniser = ClickListener(target: self, action: #selector(onViewClicked(sender:))) tapRecogniser.onClick = action self.addGestureRecognizer(tapRecogniser) } objc func onViewClicked(sender: ClickListener) { if let onClick = sender.onClick { onClick() } } } This took care of all the boilerplate code and added a simple public function to each view for click.\nTo call this function, simply call setOnClickListener to any view in your ViewController.\n//swift code in view controller view.setOnClickListener { print(\u0026#34;view clicked\u0026#34;) } No extra function required in ViewController and it will be very clean.\nComplete code ","tags":["Swift"],"title":"UIView ClickListener : Swift"},{"categories":["Gist"],"date":"December 14, 2020","permalink":"https://agrawalsuneet.github.io/gists/uiview-clicklistener-swift/","section":"gists","summary":"This particular script will help you to implement a Click listener to all UIView and its subclasses in a clean way.\nFor further explaination on how this works, please read the article UIView ClickListener : Swift.\n","tags":["Swift"],"title":"UIView ClickListener : Swift"},{"categories":["Blog"],"date":"December 4, 2020","permalink":"https://agrawalsuneet.github.io/blogs/variable-vs-object-vs-reference/","section":"blogs","summary":"Variables, Objects and References, we frequently listen to these terms while development but usually gets confused between them.\nLet\u0026rsquo;s try to understand a very basic definition along with an example for all three. The concept is similar in any object-oriented programming language but for reference, I\u0026rsquo;ll be using Java examples. Feel free to comment below if you need examples in any specific language.\nVariables Variables are named storage of any primitive data type.\nName storage means we (developers) define the name of the variable.\nPrimitive data types are something which predefined in any language like int, float, boolean etc.\nKeep in mind Int with the capital I or Float with the capital F are non-primitive data types.\nThe size of the variable depends on the type of it.\nIn Java, a char takes 2 bytes, int takes 4 bytes, float takes 8 bytes and so on.\nint age = 5; float pi = 3.14; Objects Objects are variables of non-primitive data types or user-defined classes.\nAn object can\u0026rsquo;t exist without its class.\nIt is created by the new keyword which calls the constructor of that class which ultimately assigns some memory to that object.\nIts size depends on the properties defined in that class.\nIn java, an object is created on the heap.\nEmployee emp = new Employee(); Here an object of Employee will be created by calling the new keyword. Keep in mind that technically emp is not an object, its just a reference pointing to the object which is created on heap.\nRead Refrence below to understand it better.\nReference A reference is nothing but a pointer pointing to the object. In other words, it is holding the memory address of the object created by new keyword.\nEmployee emp = new Employee(); In the same above example, emp is a reference to the object which is created using the new keyword.\nBasic differences between Variable, Object and Reference You can\u0026rsquo;t create a variable using the new keyword. Variables can\u0026rsquo;t hold null values as primitive data types doesn\u0026rsquo;t allow that. If you just write new Employee(); it will call the constructor and will even assign the memory in heap to that object but there is no reference so you can\u0026rsquo;t access it. Chaining is possible in references using the dot(.) is most of the languages. you can call a function using object reference followed by a dot(.) If you assign once reference to another like Employee emp2 = emp; it just copies the reference and but internally both the references are pointing to the same object. ","tags":["Programming-Basics"],"title":"Variable vs Object vs Reference"},{"categories":["Blog"],"date":"December 3, 2020","permalink":"https://agrawalsuneet.github.io/blogs/native-android-text-sharing-to-whatsapp-contact-in-unity/","section":"blogs","summary":"In the previous blogs, we learnt about how can we trigger native Android text, image or any other format file sharing in Unity App. A lot of you have asked me about how can we share some text directly to a WhatsApp contact.\nIf you have not read the previous medium posts, I would strongly recommend to read them first. You can read them on the links below.\nNative Android in Unity Native Android text sharing in Unity Native Android image sharing in Unity Native Android text sharing to particular app in Unity Whatsapp is something which doesn\u0026rsquo;t require any introduction. It\u0026rsquo;s a conversation app used by millions of users across the world. These million users make it unique for developers also to give special attention when it comes to sharing some message through Whatsapp.\nDuring recent times, I was asked multiple times in the comments section or even emails, if there is any possible way where we can send the text message directly to a WhatsApp contact?\nThe ideal way any app accepts text, image, video or any other format for sharing is through intent filters defined in the manifest file.\nWhatsapp also does the same and accepts all possible format (with some size and other limitations) but that will take you to a contact selection screen in Whatsapp.\nIf you want to share the text directly to a contact on WhatsApp, there is a hack which is actually not documented anywhere but using the same we can achieve it.\nThere is an API from WhatsApp which accepts phone and text and query parameters and if you call that API, it actually opens WhatsApp, check if that number exists on WhatsApp, if yes it opens conversation with that number and paste the message. If the contact or mobile numbers doesn\u0026rsquo;t exist on WhatsApp, it shows a popup saying contact doesn\u0026rsquo;t exist on WhatsApp.\nKotlin code fun onWhatsAppShareClicked(context: Context, mobileNumber: String) { val url = \u0026#34;https://api.whatsapp.com/send?phone=${mobileNumber}\u0026amp;text=You%20can%20now%20send%20me%20audio%20and%20video%20messages%20on%20the%20app%20-%20Chirp.%20%0A%0Ahttps%3A//bit.ly/chirp_android\u0026#34; val intent = Intent(Intent.ACTION_VIEW).apply { this.data = Uri.parse(url) this.`package` = \u0026#34;com.whatsapp\u0026#34; } try { context.startActivity(intent) } catch (ex : ActivityNotFoundException){ //whatsapp not installled } } Things to notice here We are not triggering the share intent. Instead, we are triggering an Action_VIEW intent with a URI which holds our url to hit. We are setting the package name exclusively to WhatsApp package in the intent. Before triggering this you need to check whether Whatsapp is installed or not using below code. Limitations We can only share text in this format. we can\u0026rsquo;t pass an image, video or any other format in this way. But we can pass an URL to an image which can be on the server. Now let\u0026rsquo;s look at the equivalent code in Unity.\n//C# code #if UNITY_ANDROID public IEnumerator ShareTextToWhatsContact() { isProcessing = true; if (!Application.isEditor) { //var url = \u0026#34;https://api.whatsapp.com/send?phone=${mobileNumber}\u0026amp;text=You%20can%20now%20send%20me%20audio%20and%20video%20messages%20on%20the%20app%20-%20Chirp.%20%0A%0Ahttps%3A//bit.ly/chirp_android\u0026#34;; var url = \u0026#34;https://api.whatsapp.com/send?phone=+919876543210\u0026amp;text=You%20can%20now%20send%20me%20audio%20and%20video%20messages%20on%20the%20app%20-%20Chirp.%20%0A%0Ahttps%3A//bit.ly/chirp_android\u0026#34;; //Create intent for action send AndroidJavaClass intentClass = new AndroidJavaClass (\u0026#34;android.content.Intent\u0026#34;); AndroidJavaObject intentObject = new AndroidJavaObject (\u0026#34;android.content.Intent\u0026#34;); intentObject.Call\u0026lt;AndroidJavaObject\u0026gt; (\u0026#34;setAction\u0026#34;, intentClass.GetStatic\u0026lt;string\u0026gt; (\u0026#34;ACTION_VIEW\u0026#34;)); //uri class AndroidJavaClass uriClass = new AndroidJavaClass(\u0026#34;android.net.Uri\u0026#34;); //set data intentObject.Call\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;setData\u0026#34;, uriClass.CallStatic\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;parse\u0026#34;, url)); //set the package to whatsapp package intentObject.Call\u0026lt;AndroidJavaObject\u0026gt; (\u0026#34;setPackage\u0026#34;, packageName); //call start activity method AndroidJavaClass unity = new AndroidJavaClass (\u0026#34;com.unity3d.player.UnityPlayer\u0026#34;); AndroidJavaObject currentActivity = unity.GetStatic\u0026lt;AndroidJavaObject\u0026gt; (\u0026#34;currentActivity\u0026#34;); currentActivity.Call (\u0026#34;startActivity\u0026#34;, intentObject); } yield return new WaitUntil (() =\u0026gt; isFocus); isProcessing = false; } #endif If you have read my previous unity blogs, you\u0026rsquo;ll understand very easily what we are doing here. We just used AndroidJavaClass and AndroidJavaObject and created the same intent object with action as ACTION_VIEW and set the data as the Uri object by parsing the url and finally triggered the startActivity function on the context.\nThe final script will look like below.\n","tags":["Unity","CSharp"],"title":"Native Android text sharing to Whatsapp contact in Unity"},{"categories":["Gist"],"date":"November 26, 2020","permalink":"https://agrawalsuneet.github.io/gists/native-android-text-sharing-to-whatsapp-contact-in-unity/","section":"gists","summary":"This particular script will help you to implement a text message sharing directly to a WhatsApp contact in Unity.\nFor further explaination on how this works, please read the article Native Android text sharing to Whatsapp contact in Unity.\n","tags":["Unity","CSharp"],"title":"Native Android text sharing to Whatsapp contact in Unity"},{"categories":["Gist"],"date":"November 23, 2020","permalink":"https://agrawalsuneet.github.io/gists/android-share-message-directly-to-whatsapp-contact/","section":"gists","summary":"This particular script will help you to implement a text message sharing directly to a WhatsApp contact in Android.\nFor further explaination on how this works, please read the article Android : Share message directly to whatsapp contact.\n","tags":["Unity","CSharp"],"title":"Android : Share message directly to whatsapp contact"},{"categories":["Slide"],"date":"November 7, 2020","permalink":"https://agrawalsuneet.github.io/slides/the-power-of-camera-apis-and-opengl-all-together/","section":"slides","summary":" Are you using the best out of your device camera and GPU in your app? Do you know how camera frames are drawn on the screen? Do you think your camera should do way more than just clicking a picture? Did you ever try to process the frames like applying filters or beautification before previewing it? How a view or camera frame is drawn on the screen? What is OpenGL? How OpenGL controls GPU rendering? What are vertex and fragment shaders? How do they affect the camera frame and preview? How can we modify the camera frames between camera APIs and previewing? What all can we do with that? Well, let\u0026rsquo;s get all these questions answered in the presentation below with our experiences and challenges we\u0026rsquo;ve faced.\nThis topic was presented remotely at Mobile Optimized 2020, Minsk, Belarus (Remote) on 07 Nov, 2020.\n","tags":["Android","Camera"],"title":"The power of Camera APIs and OpenGL all together"},{"categories":null,"date":"November 6, 2020","permalink":"https://agrawalsuneet.github.io/publicappearances/mobile-optimized-2020/","section":"publicappearances","summary":"","tags":null,"title":"Speaker at Mobile Optimized 2020"},{"categories":null,"date":"November 6, 2020","permalink":"https://agrawalsuneet.github.io/personalgamesandapps/the-last-library/","section":"personalgamesandapps","summary":"","tags":null,"title":"The Last Library"},{"categories":["Blog"],"date":"October 26, 2020","permalink":"https://agrawalsuneet.github.io/blogs/how-extension-functions-resolved/","section":"blogs","summary":"\u0026ldquo;how are extension functions resolved?\u0026rdquo;\nThis question is being asked by almost everyone both in and outside the interviews. Even I have asked this question to many candidates during the interview. The shorted or the only answer I get is \u0026ldquo;Statically\u0026rdquo;.\nWhat does statically means?\nOr how does extension functions are actually resolved?\nLet\u0026rsquo;s understand this with an example.\nConsider we have two classes BaseClass and DerivedClass. We added an extension function with the same function name to both the classes.\nopen class BaseClass class DerivedClass : BaseClass() fun BaseClass.someMethod(){ print(\u0026#34;BaseClass.someMethod\u0026#34;) } fun DerivedClass.someMethod(){ print(\u0026#34;DerivedClass.someMethod\u0026#34;) } Now if we try to call the someMethod with BaseClass reference but the actual object we passed to it will be DerivedClass object,\nfun printMessage(base : BaseClass){ base.someMethod() } //actual call printMessage(DerivedClass()) This will print BaseClass.someMethod\nConfused why? Because the extension function being called depends only on the declared type of the parameter base in printMessage method, which is the BaseClass class. This is different from runtime polymorphism as here it is resolved statically but not at the runtime. It completely depends on which class object is calling the function and the extension function of that class only will be called which is why it is called static. The basic difference between extension functions and inheritance is references are resolved statically in extension functions whereas, in inheritance, it is resolved by run time polymorphism. If you wish to read more about the differences between inheritance and extension functions, please read this blog.\nSo next time if someone asks you \u0026ldquo;how are extension functions resolved?\u0026rdquo;, Please complete your answer with an example instead of just saying it is resolved statically.\n","tags":["Kotlin"],"title":"How extension functions resolved?"},{"categories":["Blog"],"date":"October 26, 2020","permalink":"https://agrawalsuneet.github.io/blogs/infix-notation-kotlin/","section":"blogs","summary":"Ever imagined calling a public function of a class without dot and parentheses of the parameter in Kotlin. Kotlin provides infix notation with which we can call a function with the class object without using a dot and parentheses across the parameter. Using infix function provides more readability to a function similar to other operators like in, is, as in Kotlin.\nTo make a function infix notation enabled, add infix keyword before the function.\ninfix fun Int.add(b : Int) : Int = this + b val x = 10.add(20) val y = 10 add 20 // infix call But an Infix function must satisfy the following requirements\nThey must be member functions or extension functions. They must have a single parameter. The parameter must not accept a variable number of arguments and must have no default value. What if I use an infix function with other operators. You can but you should keep the priority of the operator in mind. Infix function calls have lower precedence than the arithmetic operators, type casts, and the rangeTo operator. For example\n1 add 2 + 3 is equivalent to 1 add (2 + 3) 0 until n * 2 is equivalent to 0 until (n * 2) xs union ys as Set\u0026lt;\u0026gt; is equivalent to xs union (ys as Set\u0026lt;\u0026gt;) On the other hand, infix function call’s precedence is higher than that of the boolean operators \u0026amp;\u0026amp; and ||, is- and in-checks, and some other operators. For example\na \u0026amp;\u0026amp; b xor c is equivalent to a \u0026amp;\u0026amp; (b xor c) a xor b in c is equivalent to (a xor b) in c But infix functions always require both the receiver and the parameter to be specified. When you are calling a method on the current receiver using the infix notation, you need to use this explicitly. Unlike a regular method call, this cannot be omitted. This is required to ensure unambiguous parsing.\nclass StringCollection { infix fun add(s: String) { // perform some action here } fun build() { this add \u0026#34;abc\u0026#34; // Works fine, calls the infix function add(\u0026#34;abc\u0026#34;) // Works fine, note this is not an infix call add \u0026#34;abc\u0026#34; // error: the receiver must be specified } } ","tags":["Kotlin"],"title":"Infix Notation : Kotlin"},{"categories":["Blog"],"date":"October 23, 2020","permalink":"https://agrawalsuneet.github.io/blogs/android-share-message-directly-to-whatsapp-contact/","section":"blogs","summary":"Whatsapp is something which doesn\u0026rsquo;t require any introduction. It\u0026rsquo;s a conversation app used by millions of users across the world. These million users make it unique for developers also to give special attention when it comes to sharing some message through Whatsapp.\nDuring recent times, I was asked multiple times in the comments section or even emails, if there is any possible way where we can send the text message directly to a WhatsApp contact?\nThe ideal way any app accepts text, image, video or any other format for sharing is through intent filters defined in the manifest file.\nWhatsapp also does the same and accepts all possible format (with some size and other limitations) but that will take you to a contact selection screen in Whatsapp.\nIf you want to share the text directly to a contact on WhatsApp, there is a hack which is actually not documented anywhere but using the same we can achieve it.\nThere is an API from WhatsApp which accepts \u0026lsquo;phone\u0026rsquo; and \u0026rsquo;text\u0026rsquo; and query parameters and if you call that API, it actually opens WhatsApp, check if that number exists on WhatsApp, if yes it opens conversation with that number and paste the message. If the contact or mobile numbers doesn\u0026rsquo;t exist on WhatsApp, it shows a popup saying contact doesn\u0026rsquo;t exist on WhatsApp.\nfun onWhatsAppShareClicked(context: Context, mobileNumber: String) { val url = \u0026#34;https://api.whatsapp.com/send?phone=${mobileNumber}\u0026amp;text=You%20can%20now%20send%20me%20audio%20and%20video%20messages%20on%20the%20app%20-%20Chirp.%20%0A%0Ahttps%3A//bit.ly/chirp_android\u0026#34; val intent = Intent(Intent.ACTION_VIEW).apply { this.data = Uri.parse(url) this.`package` = \u0026#34;com.whatsapp\u0026#34; } try { context.startActivity(intent) } catch (ex : ActivityNotFoundException){ //whatsapp not installled } } Things to notice here We are not triggering the share intent. Instead, we are triggering an Action_VIEW intent with a URI which holds our url to hit. We are setting the package name exclusively to WhatsApp package in the intent. Before triggering this you need to check whether Whatsapp is installed or not using below code. fun isPackageInstalled(context: Context, packageName: String): Boolean { return try { context.packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES) true } catch (ex: Exception) { false } } Limitations We can only share text in this format. we can\u0026rsquo;t pass an image, video or any other format in this way. But we can pass an URL to an image which can be on the server. Complete code ","tags":["Kotlin"],"title":"Android : Share message directly to whatsapp contact"},{"categories":["Gist"],"date":"October 15, 2020","permalink":"https://agrawalsuneet.github.io/gists/native-android-image-sharing-in-unity-using-fileprovider/","section":"gists","summary":"This particular script will help you to implement native Android image sharing using Android\u0026rsquo;s FileProvider in Unity. This is a fix for “android.os.FileUriExposedException” in Android 8 (Oreo) and above.\nWe use all the native classes of Android in Unity using AndroidJavaClass and AndroidJavaObject and perform the Android\u0026rsquo;s ACTION_SEND with EXTRA_SUBJECT, EXTRA_TEXT and EXTRA_STREAM. The content type is set to image/png in the below example but you can change it to any type and share other formats also.\nFor further explaination on how this works, please read the article Native Android image sharing in Unity using FileProvider.\n","tags":["Unity","CSharp"],"title":"Native Android image sharing in Unity using FileProvider"},{"categories":["Gist"],"date":"October 12, 2020","permalink":"https://agrawalsuneet.github.io/gists/native-android-text-sharing-to-particular-app-in-unity/","section":"gists","summary":"This particular script will help you to implement native Android text sharing to a particular app in Unity.\nWe use all the native classes of Android in Unity using AndroidJavaClass and AndroidJavaObject and perform the Android\u0026rsquo;s ACTION_SEND with EXTRA_SUBJECT and EXTRA_TEXT, and share the content to a particular app with package name.\nFor further explaination on how this works, please read the article Native Android share to a particular app in Unity.\n","tags":["Unity","CSharp"],"title":"Native Android text sharing to particular app in Unity"},{"categories":["Gist"],"date":"October 11, 2020","permalink":"https://agrawalsuneet.github.io/gists/native-android-image-sharing-in-unity/","section":"gists","summary":"This particular script will help you to implement native Android image sharing in Unity.\nWe use all the native classes of Android in Unity using AndroidJavaClass and AndroidJavaObject and perform the Android\u0026rsquo;s ACTION_SEND with EXTRA_SUBJECT, EXTRA_TEXT and EXTRA_STREAM. The content type is set to image/png in the below example but you can change it to any type and share other formats also.\nFor further explaination on how this works, please read the article Native Android screenshot/image sharing in Unity.\n","tags":["Unity","CSharp"],"title":"Native Android image sharing in Unity"},{"categories":["Gist"],"date":"October 10, 2020","permalink":"https://agrawalsuneet.github.io/gists/native-android-text-sharing-in-unity/","section":"gists","summary":"This particular script will help you to implement native Android text sharing in Unity.\nWe use all the native classes of Android in Unity using AndroidJavaClass and AndroidJavaObject and perform the Android\u0026rsquo;s ACTION_SEND with EXTRA_SUBJECT and EXTRA_TEXT.\nFor further explaination on how this works, please read the article Native Android text sharing in Unity.\n","tags":["Unity","CSharp"],"title":"Native Android text sharing in Unity"},{"categories":["Gist"],"date":"October 9, 2020","permalink":"https://agrawalsuneet.github.io/gists/native-android-in-unity/","section":"gists","summary":"This particular script will help you to implement basic native Android in Unity.\nThis show an example of showing a native Android\u0026rsquo;s Toast in unity using AndroidJavaClass and AndroidJavaObject.\nFor further explaination on how this works, please read the article Native Android in Unity.\n","tags":["Unity","CSharp"],"title":"Native Android in Unity"},{"categories":["Blog"],"date":"September 13, 2020","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-extension-property/","section":"blogs","summary":"Extension functions are really-really helpful while writing code in Kotlin. You don\u0026rsquo;t have to extend the class but you can add the functionality to even a final (non-open) class which will be resolved statically but how about extension properties.\nA very interesting question asked to me during an interview or even a general situation where we need to add a property (variable) to an existing class without extending it.\nIs it even possible? Can we add a property/variable as an extension to an existing class?\nAccording to the theory of extension functions, this is not possible since you can only add the extension functions but not properties, but there is a workaround which can solve the purpose.\nLet\u0026rsquo;s try to understand that workaround first and then talk about the limitations.\nSay there is a class name Temperature which only has one property tempInCelsius which it takes as a parameter in the constructor.\nclass Temperature(var tempInCelsius: Float) Now I want to add one more property tempInFahrenheit which will be holding the same value of temperature but in Fahrenheit.\nI actually can\u0026rsquo;t add a property for the same but I can add getter and setter which are nothing but the extension functions to the same.\nvar Temperature.tempInFahrenheit: Float get() = (tempInCelsius * 9 / 5) + 32 set(value) { tempInCelsius = (value - 32) * 5 / 9 } and I can call this property simply like any other property of that class.\nval temp = Temperature(32f) println(temp.tempInFahrenheit) temp.tempInFahrenheit = 90f println(temp.tempInCelsius) What exactly we did? We didn\u0026rsquo;t add any property but using the syntactical sugar, we added one setter and one getter under the name of one variable, which ultimately read and writes to one of the existing variables.\nThis setter function takes a float value and the setter also return the float value. This might look like a new property but this is not. This is just a set of new getter setter.\nWhat are the limitations? Since we never added an actual property, we can\u0026rsquo;t use the backing field.\nvar Temperature.tempInFahrenheit: Float = 32 \u0026lt;e\u0026gt;//compilation error\u0026lt;/e\u0026gt; \u0026lt;e\u0026gt;initializers are not allowed for extension properties\u0026lt;/e\u0026gt; var Temperature.tempInFahrenheit: Float get() = field \u0026lt;e\u0026gt;//compilation error\u0026lt;/e\u0026gt; set(value) { field = value \u0026lt;e\u0026gt;//compilation error\u0026lt;/e\u0026gt; } Also, we can only do some processing but to store that value we need some existing variable only within the class. We can never save the value in the so-called extension property variable (tempInFahrenheit in our case) as at the end it is not a property.\nSo to answer the question, there is no possible way you can add an extension property with backing field or which can store value but using syntactical sugar, you can add a property which ultimately is a getter or/and setter which can do the job for you.\nRead more about extension functions on the below links.\nExtensions in Kotlin How extension functions resolved? Inheritance vs Extension functions ","tags":["Kotlin"],"title":"Kotlin Extension Property"},{"categories":["Blog"],"date":"August 14, 2020","permalink":"https://agrawalsuneet.github.io/blogs/native-android-text-sharing-to-particular-app-in-unity/","section":"blogs","summary":"In the previous blogs Native Android text sharing in Unity and Native Android image sharing in Unity we learnt about how to share some text or screenshot to other apps in a Unity app targeting Android platforms. In this post will target sharing the same text or image to some particular app directly.\nIf you have not read the previous blogs, I would strongly recommend to read them first. You can read them on the links below.\nNative Android in Unity Native Android text sharing in Unity Native Android image sharing in Unity Direct accessibility is a feature that usually boosts the numbers as it reduces the number of clicks in an app. Sharing your score directly on some app can be one of them. Let’s take an example of WhatsApp in our case. There can be a use case where we want to provide a feature in the Unity app where a user can share their score in the form of text or image directly to WhatsApp.\nAndroid provides the functionality where while sharing the text or image, we can provide the package name of the app to which we want to share directly. But before performing direct sharing, we need to confirm that the particular app is installed in the user’s device.\nThis can be done by getting a list of all the packages installed on users device and checking if the package is we are looking for is available in that list.\nThe Jave code for this check would be\n//Java public boolean checkIfAppInstalled(Context context, String packageName) { List\u0026lt;PackageInfo\u0026gt; list = context.getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES); for (PackageInfo item : list){ if (item.packageName.equalsIgnoreCase(packageName)){ return true; } } return false; } And the Kotlin code would be\n//Kotlin fun checkIfAppInstalled(context: Context, packageName: String): Boolean { val list = context.packageManager .getInstalledPackages(PackageManager.GET_ACTIVITIES) for (item in list) { if (item.packageName.equals(packageName, ignoreCase = true){ return true } } return false } But where can I get the package name of the app I want to share on? You can visit the Play Store page of that particular app and get the package name from the URL of that page.\nIt will be the marked as id=\u0026lt;packagename\u0026gt;\nIn the case of WhatsApp, it will be com.whatsapp\nNow let’s try to achieve the same functionality of checking whether the sharing app is installed on the user’s device.\nThe C# code in Unity for the same will be\n//C# code private bool CheckIfAppInstalled(){ #if UNITY_ANDROID string packageName = \u0026#34;com.whatsapp\u0026#34;; //create a class reference of unity player activity AndroidJavaClass unityActivity = new AndroidJavaClass (\u0026#34;com.unity3d.player.UnityPlayer\u0026#34;); //get the context of current activity AndroidJavaObject context = unityActivity.GetStatic\u0026lt;AndroidJavaObject\u0026gt; (\u0026#34;currentActivity\u0026#34;); //get package manager reference AndroidJavaObject packageManager = context.Call\u0026lt;AndroidJavaObject\u0026gt; (\u0026#34;getPackageManager\u0026#34;); //get the list of all the apps installed on the device AndroidJavaObject appsList = packageManager.Call\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;getInstalledPackages\u0026#34;, 1); //get the size of the list for app installed apps int size = appsList.Call\u0026lt;int\u0026gt; (\u0026#34;size\u0026#34;); for (int i = 0; i \u0026lt; size; i++) { AndroidJavaObject appInfo = appsList.Call\u0026lt;AndroidJavaObject\u0026gt; (\u0026#34;get\u0026#34;, i); string packageNew = appInfo.Get\u0026lt;string\u0026gt; (\u0026#34;packageName\u0026#34;); if (packageNew.CompareTo (packageName) == 0) { return true; } } return false; #endif } Now that we got a check if the app is installed on the user’s device or not, we can share to the app (WhatsApp in our case) directly by simply setting the package to the intent. Rest all will still be the same as it was in the case of text sharing or screenshot sharing in Unity.\nThe java code for the same is\n//Jave Intent intent = new Intent(); intent.setPackage(packageName); and the Kotlin code would be\n//Kotlin val intent = Intent() intent.`package` = packageName And the equivalent code in C# for Unity would be\n//C# for Unity string packageName = \u0026#34;com.whatsapp\u0026#34;; AndroidJavaObject intentObject = new AndroidJavaObject (\u0026#34;android.content.Intent\u0026#34;); intentObject.Call (\u0026#34;setPackage\u0026#34;, packageName); And this will open the WhatsApp directly for sharing.\nThe final script will look like below.\nThe above script can be used in any unity app targeting Android platform to share a text or high score natively to any particular app in Android.\nUpdate: Native Android image sharing in Unity Native Android image sharing in Unity using FileProvider ","tags":["Unity","CSharp"],"title":"Native Android text sharing to particular app in Unity"},{"categories":["Slide"],"date":"July 26, 2020","permalink":"https://agrawalsuneet.github.io/slides/low-level-design-tic-tac-toe/","section":"slides","summary":"System designing is the process of designing system elements such as architectures, modules, components, different interfaces of those components. Its the process of defining the lowest level entities in a software. It is the backbone of any software.\nSystem design is of two types\nLow level design High level design There is no fine line or a separator difference between the two that upto this part of software is low level and above this is high level but mostly,\nLow level defines reusable entities and relationship between them as well as the object creation and dependencies.\nHigh level defines functionalities into components and the management of those components into a system.\nThese concepts are well explained in the below presentation along with an example of tic-tac-toe.\n","tags":["Programming-Basics"],"title":"Low Level Design : Tic-Tac-Toe"},{"categories":null,"date":"July 11, 2020","permalink":"https://agrawalsuneet.github.io/personalgamesandapps/fireblock/","section":"personalgamesandapps","summary":"","tags":null,"title":"FireBlock"},{"categories":["Slide"],"date":"July 11, 2020","permalink":"https://agrawalsuneet.github.io/slides/how-can-i-migrate-my-android-code-from-java-to-kotlin/","section":"slides","summary":"In continuation of the previews session for Google Accelerator program on the topic Java or Kotlin. what do you use? today we are going to look at how can you migrate the codebase from java to Kotlin and what are the common mistake made by developers while doing the same.\nDevelopers know the benefit of Kotlin over Java for Android app development but they hesitate to try it or even sometimes doesn\u0026rsquo;t know how to start using it in their existing code base. It is very easy to start with at the same time you don\u0026rsquo;t have to migrate the entire codebase in one shot. Instead, you can start writing new features using Klotlin and once you are familiar with Kotlin, you can slowly start the migration of older code.\nHow easy it is to migrate my codebase from Java to Kotlin? What all tools are available to do the same? How Android studio can help me? Do I need to change the entire codebase in one shot? What things I should be taking care of while migration? WWhat are the common mistakes made by developers while migration? What about the new feature development and the release process currently going on? Should your product managers be worried about this migration? Let\u0026rsquo;s try to understand how can we start using Kotlin in existing code base effeciently.\nThis topic was presented remotely as a part of Android Bootcamps part of Google for Startup Program on 11th July, 2020.\n","tags":["Android"],"title":"How can I migrate my Android code from Java to Kotlin?"},{"categories":null,"date":"July 11, 2020","permalink":"https://agrawalsuneet.github.io/publicappearances/google-startup-program-1/","section":"publicappearances","summary":"","tags":null,"title":"Speaker at Android Bootcamps part of Google for Startup Program"},{"categories":null,"date":"July 5, 2020","permalink":"https://agrawalsuneet.github.io/personalgamesandapps/lets-challenge/","section":"personalgamesandapps","summary":"","tags":null,"title":"Lets Challenge"},{"categories":["Slide"],"date":"June 6, 2020","permalink":"https://agrawalsuneet.github.io/slides/java-or-kotlin-what-do-you-use/","section":"slides","summary":"Kotlin is something which was introduced as an official language for Android development in Google I/O 2017. Since then it has grown and evolved a lot. It has multiple benefits and on top of everything, it\u0026rsquo;s really easy to use.\nIts been three years, still devs or some companies hesitate to use it.\nWhat is Kotlin? How can it benefit your startup? Why devs resist themselves moving from Java to Kotlin language? How easy Kotlin is in terms of learning? How Kotlin can make their life super easy? Why android devs should at least try once before saying NO? How can they start using it today in their existing codebase itself? Let\u0026rsquo;s try to understand what are the benefits as well as challenges faced by devs while using Kotlin, and how can we overcome those challenges?\nThis topic was presented remotely as a part of Android Bootcamps part of Google for Startup Program on 6th June, 2020.\n","tags":["Android"],"title":"Java or Kotlin, What do you use?"},{"categories":null,"date":"June 6, 2020","permalink":"https://agrawalsuneet.github.io/publicappearances/google-startup-program-2/","section":"publicappearances","summary":"","tags":null,"title":"Speaker at Android Bootcamps part of Google for Startup Program"},{"categories":null,"date":"June 6, 2020","permalink":"https://agrawalsuneet.github.io/personalgamesandapps/ufo/","section":"personalgamesandapps","summary":"","tags":null,"title":"UFO"},{"categories":["Slide"],"date":"May 30, 2020","permalink":"https://agrawalsuneet.github.io/slides/object-oriented-programming-oop-concepts/","section":"slides","summary":"Object-oriented programming (OOP) concepts are something which are fundamentals of any Object-oriented programming language. These concepts give you the power to structure your code in such a way that it\u0026rsquo;s well optimized, reusable, efficient, future proof and much more.\nThe basic concepts of Object-oriented programming are,\nAbstraction Encapsulation Dependency Association Composition Aggregation Inheritance Extensibility Run-Time Polymorphism (RTP) Substitutability Overriding Packaging Please note that these concepts are not language specific but applies to all object oriented programming languages.\nThese concepts are well explained in the below presentation.\n","tags":["Programming-Basics"],"title":"Object-Oriented Programming (OOP) Concepts"},{"categories":["Blog"],"date":"April 27, 2020","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-apply-function/","section":"blogs","summary":"In continuation to my previous post where I explained about Kotlin let function, let\u0026rsquo;s try to understand today about apply function today.\nJust to recap, Scope functions are nothing but the functions which define to the scope of the calling object. We can apply operations on that object within that scope and return the object itself from that scope function or we can even return the result of operation or operations from the scope function.\nThere are a few scope functions\nlet with run apply also To keep this article short and to the point, we will talk only about apply in this article and all the use cases around it.\napply scope function is used to configure the object once initialized and returns the object itself. The context object is available inside the apply function as this.\nTo understand apply function lets look at the implementation of apply function first.\n/** * Calls the specified function [block] * with `this` value as its receiver * and returns `this` value. * */ @kotlin.internal.InlineOnly public inline fun \u0026amp;lt;T\u0026amp;gt; T.apply(block: T.() -\u0026gt; Unit): T { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } block() return this } apply is an extension function to Template class which takes a lambda as a parameter, apply contract on it, execute the lambda function within the scope of calling object and ultimately return the same calling object of Template class itself.\nThis clarifies a few things 1. The return type of the `apply` function is nothing but the same calling object. 2. Since its an extension function to the Template class, it can be called on any object. Now let\u0026rsquo;s understand what is the contract The contract is nothing but a contract applied to the passed lambda as a parameter.\n/** * Specifies the contract of a function. * * The contract description must be at the beginning of a function and have at least one effect. * * Only the top-level functions can have a contract for now. * * @param builder the lambda where the contract of a function is described with the help of the [ContractBuilder] members. * @ContractsDsl @ExperimentalContracts @InlineOnly @SinceKotlin(\u0026#34;1.3\u0026#34;) @Suppress(\u0026#34;UNUSED_PARAMETER\u0026#34;) public inline fun contract(builder: ContractBuilder.() -\u0026gt; Unit) { } This is exactly the same contract as to any other scope function. This superimposes some conditions on the lambda we passed as a parameter to the apply function. What conditions it superimposed, we need to check the parameter of the contract\nAnd what contract applied in the apply function ? /** * Specifies that the function parameter [lambda] is invoked in place. * * This contract specifies that: * 1. the function [lambda] can only be invoked during the call of the owner function, * and it won\u0026#39;t be invoked after that owner function call is completed; * 2. _(optionally)_ the function [lambda] is invoked the amount of times specified by the [kind] parameter, * see the [InvocationKind] enum for possible values. * * A function declaring the `callsInPlace` effect must be _inline_. * */ /* @sample samples.contracts.callsInPlaceAtMostOnceContract * @sample samples.contracts.callsInPlaceAtLeastOnceContract * @sample samples.contracts.callsInPlaceExactlyOnceContract * @sample samples.contracts.callsInPlaceUnknownContract */ @ContractsDsl public fun \u0026lt;R\u0026gt; callsInPlace(lambda: Function\u0026lt;R\u0026gt;, kind: InvocationKind = InvocationKind.UNKNOWN): CallsInPlace It superimposes 2 conditions\nThe lambda will be invoked only during owner function call and it won\u0026rsquo;t be called once the owner function is completed. The number of times this lambda function will be invoked (which is exactly once in our case) which is an enum. The above conditions are clear from there definition itself.\nSo basically, apply function will be called only during the owner function will be called. called ONLY ONCE. called on the calling object. and will return the object itself on which the apply function is called. Now let\u0026rsquo;s look at the use cases apply is recommended for lambdas that mainly operate on the object members or call its functions or assign properties. In short, it is mostly used for object configurations.\nclass Employee { var firstName: String = \u0026#34;\u0026#34; var age: Int = 0 } val employee = Employee().apply{ firstName = \u0026#34;Suneet Agrawal\u0026#34; age = 27 } println(\u0026#34;name:${employee.firstName} age:${employee.age}\u0026#34; ) Please note that we can even point to the calling object by this but we can\u0026rsquo;t use a named parameter in apply.\nval employee = Employee().apply{ this.firstName = \u0026#34;Suneet Agrawal\u0026#34; this.age = 27 } We can avoid the use of this pointer or use it to avoid the conflicts between other properties or objects with the same name within that class. It points to the calling object only.\nThere is no need to call the return from apply function. Although there won\u0026rsquo;t be any compilation error. Since the return type of the lambda passed in apply function is Unit, no point of calling return.\nval employee = Employee().apply{ this.firstName = \u0026#34;Suneet Agrawal\u0026#34; this.age = 27 return //this line doesn\u0026#39;t make sense at all } We can even chain the apply function\nclass Employee { var firstName: String = \u0026#34;\u0026#34; var age: Int = 0 fun somefunction(){ //do something here } } Employee().apply{ this.firstName = \u0026#34;Suneet Agrawal\u0026#34; this.age = 27 }.somefunction() Two things to keep in mind about apply, apply uses the context as this and we can not use a named parameter instead of this. apply returns the calling object itself. ","tags":["Kotlin"],"title":"Kotlin apply function"},{"categories":["Blog"],"date":"April 22, 2020","permalink":"https://agrawalsuneet.github.io/blogs/collections-in-kotlin/","section":"blogs","summary":"Collections are a common concept for most programming languages. It is a way of storing similar data types in a single object and iterate over it. Similar to any other language, Kotlin also has Collection defined in kotlin.collections package.\nTypes of Collection in Kotlin There are two types of collection in Kotlin\nImmutable The one which cant be modified once the object is created. We can just iterate over them or create a copy of them but we cant modify the actual one.\nMutable These can be modified means that we can add items or elements to the original object once they are created along with iteration and copy.\nTo understand the immutable and mutable types, Let`s try to understand the interfaces in the Collection package of Kotlin first.\nKeep in mind we are only talking about the interfaces and implementations of Kotlin. Although, Android is compatible with Java also and we can use the Collections of Java also defined in java.util package but Kotlin has a separate Collection and a few of the implementations like Vector, CopyOnWriteArrayList, CopyOnWriteArraySet and many more are not there in Kotlin.\nIterable The parent of all the interfaces is Iterable. As the name suggests, it confirms the functionality of iteration by the class which implements it. This has an abstract function iterator that returns the Iterator reference object.\n/** * Classes that inherit from this interface can be represented as a sequence of elements that can * be iterated over. * @param T the type of element being iterated over. The iterator is covariant on its element type. */ public interface Iterable\u0026lt;out T\u0026gt; { /** * Returns an iterator over the elements of this object. */ public operator fun iterator(): Iterator\u0026lt;T\u0026gt; } MutableIterable Iterable is further extended by another interface ie MutableIterable. This particular interface confirms the iteration along with the mutability. This means the object can be mutated or modified.\n/** * Classes that inherit from this interface can be represented as a sequence of elements that can * be iterated over and that supports removing elements during iteration. * @param T the type of element being iterated over. The mutable iterator is invariant on its element type. */ public interface MutableIterable\u0026lt;out T\u0026gt; : Iterable\u0026lt;T\u0026gt; { /** * Returns an iterator over the elements of this sequence that supports removing elements during iteration. */ override fun iterator(): MutableIterator\u0026lt;T\u0026gt; } Collection The Iterable is also extended by the Collection interface which provides the basic functions like size, isEmpty, contains and containsAll.\n/** * A generic collection of elements. Methods in this interface support only read-only access to the collection; * read/write access is supported through the MutableCollection interface. * @param E the type of elements contained in the collection. The collection is covariant on its element type. */ public interface Collection\u0026lt;out E\u0026gt; : Iterable\u0026lt;E\u0026gt; { // Query Operations /** * Returns the size of the collection. */ public val size: Int /** * Returns `true` if the collection is empty (contains no elements), `false` otherwise. */ public fun isEmpty(): Boolean /** * Checks if the specified element is contained in this collection. */ public operator fun contains(element: @UnsafeVariance E): Boolean override fun iterator(): Iterator\u0026lt;E\u0026gt; // Bulk Operations /** * Checks if all elements in the specified collection are contained in this collection. */ public fun containsAll(elements: Collection\u0026lt;@UnsafeVariance E\u0026gt;): Boolean } MutableCollection MutableIterable and Collection are further extended by MutableCollection which provides mutability to the Collection like add, remove, addAll, removeAll, retainAll, clear.\n/** * A generic collection of elements that supports adding and removing elements. * * @param E the type of elements contained in the collection. The mutable collection is invariant on its element type. */ public interface MutableCollection\u0026lt;E\u0026gt; : Collection\u0026lt;E\u0026gt;, MutableIterable\u0026lt;E\u0026gt; { // Query Operations override fun iterator(): MutableIterator\u0026lt;E\u0026gt; // Modification Operations /** * Adds the specified element to the collection. * * @return `true` if the element has been added, `false` if the collection does not support duplicates * and the element is already contained in the collection. */ public fun add(element: E): Boolean /** * Removes a single instance of the specified element from this * collection, if it is present. * * @return `true` if the element has been successfully removed; `false` if it was not present in the collection. */ public fun remove(element: E): Boolean // Bulk Modification Operations /** * Adds all of the elements of the specified collection to this collection. * * @return `true` if any of the specified elements was added to the collection, `false` if the collection was not modified. */ public fun addAll(elements: Collection\u0026lt;E\u0026gt;): Boolean /** * Removes all of this collection`s elements that are also contained in the specified collection. * * @return `true` if any of the specified elements was removed from the collection, `false` if the collection was not modified. */ public fun removeAll(elements: Collection\u0026lt;E\u0026gt;): Boolean /** * Retains only the elements in this collection that are contained in the specified collection. * * @return `true` if any element was removed from the collection, `false` if the collection was not modified. */ public fun retainAll(elements: Collection\u0026lt;E\u0026gt;): Boolean /** * Removes all elements from this collection. */ public fun clear(): Unit } List List is an ordered collection where we can access the elements by indices. List interface is extended by Collection interface.\nMutableList MutableList is also an ordered collection where we can access the elements by indices but this is mutable. This means we can modify the object created, we can add remove elements it in. MutableList is extended by MutableCollection interface.\nSet Set is an unordered collection of unique elements. The order of insertion of elements or items is not maintained in Set. It is extended by Collection interface.\nMutableSet MutableSet is also an unordered collection of unique elements but this is mutable. The order of insertion of elements or items is also not maintained in MutableSet. It is extended by MutableCollection interface.\nMap Map is a set of key-value pairs where Keys are unique, and each of them maps to exactly one value. The values can be duplicates but the keys will be unique. The order of insertion of elements or items is not maintained in the map also. Map is immutable means we cant modify the object(add or remove elements) once its created.\nThis has no connection with any of the above interfaces but this has two objects, keys and values which are of types Set and Collection respectively.\n/** * A collection that holds pairs of objects (keys and values) and supports efficiently retrieving * the value corresponding to each key. Map keys are unique; the map holds only one value for each key. * Methods in this interface support only read-only access to the map; read-write access is supported through * the [MutableMap] interface. * @param K the type of map keys. The map is invariant on its key type, as it * can accept key as a parameter (of [containsKey] for example) and return it in [keys] set. * @param V the type of map values. The map is covariant on its value type. */ public interface Map\u0026lt;K, out V\u0026gt; { ... /** * Returns a read-only [Set] of all keys in this map. */ public val keys: Set\u0026lt;K\u0026gt; /** * Returns a read-only [Collection] of all values in this map. Note that this collection may contain duplicate values. */ public val values: Collection\u0026lt;V\u0026gt; ... } MautableMap MutableMap is similar to Map only which holds key-value but this is mutable. This also has no connection with any of the above interfaces.\nNow that we have a clear picture of interfaces, lets look at how can we initialise the respective objects in Kotlin\nImmutable and Mutable List //Immutable Lists val list = listOf(1, 2, 3) val listOfNonNull = listOfNotNull(1, 2, 3) //Mutable Lists val arrayList = ArrayList\u0026lt;Int\u0026gt;() val arrayList2 = arrayListOf(1, 2, 3) val mutableList = mutableListOf(1, 2, 3) Immutable and Mutable Set //Immutable Sets val set = setOf(1, 2, 3) //Mutable Sets val hashSet = hashSetOf(1, 2, 3) val mutableSet = mutableSetOf(1, 2, 3) val linkedSet = linkedSetOf(1, 2, 3) Immutable and Mutable Map //Immutable Maps val map = mapOf(1 to \u0026#34;One\u0026#34;, 2 to \u0026#34;Two\u0026#34;, 3 to \u0026#34;Three\u0026#34;) //Mutable Maps val hashMap = hashMapOf(1 to \u0026#34;One\u0026#34;, 2 to \u0026#34;Two\u0026#34;, 3 to \u0026#34;Three\u0026#34;) val mutableMap = mutableMapOf(1 to \u0026#34;One\u0026#34;, 2 to \u0026#34;Two\u0026#34;, 3 to \u0026#34;Three\u0026#34;) val sortedMap = sortedMapOf(1 to \u0026#34;One\u0026#34;, 2 to \u0026#34;Two\u0026#34;, 3 to \u0026#34;Three\u0026#34;) ","tags":["Kotlin"],"title":"Collections in Kotlin"},{"categories":["Blog"],"date":"March 29, 2020","permalink":"https://agrawalsuneet.github.io/blogs/partial-class-in-csharp-partial-modifier/","section":"blogs","summary":"Think about a situation where two or more developers need to modify the same class or add new functionalities to the same class. Or assume they need to implement interfaces to the same class. There will be a merge conflict which needs to be resolved manually or using some tool.\nOr think about a situation where an automatically generated code needs to be added into some class without having to recreate the source file.\nA similar kind of challenge We faced while working on a Unity project where we two of the devs were constantly working on some same classes. The only way to avoid conflicts was by separating the areas in the class where we both will add the functionalities. Later I came to know about the partial class which was helpful in such situations.\nWhat is a Partial class? A partial class is a special type of class where a single class can be split into multiple .cs file and while compilation, all the functionalities of same partial classes written in different .cs files will be merged and then compile it.\nIt provides you with functionality where you can split your class into different files based on the requirement and usability.\nIn short, partial class in a way of writing a single class into multiple .cs files and these files will be combined when the application is compiled.\nA partial class is created by using a partial keyword. This keyword is also useful to split the functionality of methods, interfaces, or structure into multiple files.\n//Someclass1.cs public partial class SomeClass { // code private void function1(){ } } //Someclass2.cs public partial class SomeClass { // code private void function2(){ } } //final compiled code public class SomeClass { private void function1(){ } private void function2(){ } } Requirements of Partial modifier A partial modifier can be added to a class or an interface or a struct. Every part of the partial class definition should be in the same assembly and namespace, but we can use different source file name. All the parts must have the same accessibility for example public or private, etc. If any part is declared abstract, sealed or base type then the whole class is declared of the same type. The partial modifier can only appear immediately before the keywords class, struct, or interface. Nested partial types are allowed. Different parts can have different base types like implementing different interfaces and the final class will inherit all the base types. Advantages of Partial class With the concept of partial classes, we can better the code structure like by separating business logic and UI implementation within the same class. Can avoid conflicts if multiple developers working on the same class or interface or struct. When we working with automatically generated source, code can be added to the class without having to recreate the source file. For example, Visual Studio separates HTML code for the UI and server-side code into two separate files: .aspx and .cs files. ","tags":["CSharp"],"title":"Partial class in C# (partial modifier)"},{"categories":["Blog"],"date":"March 3, 2020","permalink":"https://agrawalsuneet.github.io/blogs/difference-between-any-unit-and-nothing-kotlin/","section":"blogs","summary":"We all know about three classes Any, Unit and Nothing in Kotlin which have their own functionality and use cases but we usually confuse between the differences among them and when to use what.\nLet try to understand what are these, when to use what and how these are different from one another.\nAny Any is an open class and by default the superclass for all the classes, whether we define it explicitly or not. This is similar to the Object class in Java which is the superclass for each and every class.\n/** * The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass. */ public open class Any { public open operator fun equals(other: Any?): Boolean public open fun hashCode(): Int public open fun toString(): String } Any has 3 functions\nequals hashCode toString All three functions are well-known functions which can be overridden in any class.\nequals /** * Indicates whether some other object is \u0026#34;equal to\u0026#34; this one. Implementations must fulfil the following * requirements: * * * Reflexive: for any non-null value `x`, `x.equals(x)` should return true. * * Symmetric: for any non-null values `x` and `y`, `x.equals(y)` should return true if and only if `y.equals(x)` returns true. * * Transitive: for any non-null values `x`, `y`, and `z`, if `x.equals(y)` returns true and `y.equals(z)` returns true, then `x.equals(z)` should return true. * * Consistent: for any non-null values `x` and `y`, multiple invocations of `x.equals(y)` consistently return true or consistently return false, provided no information used in `equals` comparisons on the objects is modified. * * Never equal to null: for any non-null value `x`, `x.equals(null)` should return false. */ public open operator fun equals(other: Any?): Boolean equals functions check if the object is equal to the object passed in parameter. There are different criteria on which equals function checks the equality but we can override this function in any class.\nhashCode /** * Returns a hash code value for the object. The general contract of `hashCode` is: * * * Whenever it is invoked on the same object more than once, the `hashCode` method must consistently return the same integer, provided no information used in `equals` comparisons on the object is modified. * * If two objects are equal according to the `equals()` method, then calling the `hashCode` method on each of the two objects must produce the same integer result. */ public open fun hashCode(): Int hashCode returns a unique integer for each and every object of that class. This function is also open and we can override it according to our use case.\ntoString /** * Returns a string representation of the object. */ public open fun toString(): String This is the most commonly overridden function which is used to represent the object in string form. This is again open and we can override it according to the use case.\nWe can even create an object of Any class and use any of the above functions.\nval any: Any = Any() any.equals(Any()) any.hashCode() any.toString() Unit Unit class is an object class which means it a singleton class having only one object.\n/** * The type with only one value: the `Unit` object. This type corresponds to the `void` type in Java. */ public object Unit { override fun toString() = \u0026#34;kotlin.Unit\u0026#34; } Unit is exactly equivalent to the void type in Java. We can explicitly add Unit as the return type for functions returning void.\nfun doSomething() { //do something here } fun doSomething() : Unit { //do something here } Both the above functions are absolutely the same but for the second one, there will a warning stating\nRedundant \u0026#39;Unit\u0026#39; return type We can\u0026rsquo;t extend Unit class.\nobject AnotherUnit : Unit { } class AnotherUnit : Unit { } //both above will have Error: Compilation error \u0026#34;Cannot inherit from a Singleton\u0026#34; We can\u0026rsquo;t even create an object of it.\nval unit: Unit = Unit() unit.toString() //error: Compilation error in first line \u0026#34;Expression \u0026#39;Unit\u0026#39; of type \u0026#39;Unit\u0026#39; cannot be invoked as a function. The funciton \u0026#39;invoke()\u0026#39; is not found\u0026#34; Nothing Nothing is used to represent a value which will never exist.\nThis is has a private constructor and also cannot be extended.\n/** * Nothing has no instances. You can use Nothing to represent \u0026#34;a value that never exists\u0026#34;: for example, * if a function has the return type of Nothing, it means that it never returns (always throws an exception). */ public class Nothing private constructor() It is used to define a function return type which is going to throw an exception every time.\nfun iWillAlwaysThrowException() = throw Exception(\u0026#34;Unnecessary Exception\u0026#34;) //The ebove function will show a Error: compilation error \u0026#39;Nothing\u0026#39; return type needs to be specified explicitely and the correct syntax will be\nfun iWillAlwaysThrowException() : Nothing = throw Exception(\u0026#34;Unnecessary Exception\u0026#34;) The best example of Nothing is in TODO function.\n/** * Always throws [NotImplementedError] stating that operation is not implemented. */ @kotlin.internal.InlineOnly public inline fun TODO(): Nothing = throw NotImplementedError() /** * Always throws [NotImplementedError] stating that operation is not implemented. * * @param reason a string explaining why the implementation is missing. */ @kotlin.internal.InlineOnly public inline fun TODO(reason: String): Nothing = throw NotImplementedError(\u0026#34;An operation is not implemented: $reason\u0026#34;) Differences between Any, Unit and Nothing Any Any is by default the superclass of all the classes and has 3 functions: equals, hashCode and toString. This is equal to Object class in Java. We can create an object of Any class directly or even override these functions in any other class. Unit Unit class is a singleton class, we can\u0026rsquo;t extend or even create an object of it. Unit class in equal to void type in Java. The superclass of Unit is Any and it has overridden toString method. Nothing Nothing is non-open (final class) which can\u0026rsquo;t be extended and its constructor is also private that means we can\u0026rsquo;t create the object also. This is usually used to represent the return type of function which will always throw an exception. The superclass of Nothing is Any. ","tags":["Kotlin"],"title":"Destructuring Declarations in Kotlin"},{"categories":["Blog"],"date":"February 29, 2020","permalink":"https://agrawalsuneet.github.io/blogs/why-let-function-is-an-extension-to-template-class/","section":"blogs","summary":"After reading my last blog about Kotlin let function, a lot of developers have asked me about, why let is an extension to Template class but not to Any class?\nNot only let, but other helper functions like apply, also, takeIf and takeUnless are also extension functions to the Template class.\nThe question is why? Any is the base class for all the classes, similar to java.lang.Object class in Java, even if you extend it or not. So if we want any of these functionalities in any class, Kotlin could have added these functions as an extension function to Any class but not to Template class.\nSince we all know that Kotlin is an official language for Android which also supports Java.\nTo provide these functionalities for java objects also, which extends Object class, Kotlin has added these functions as an extension function to Template class.\nIf these were an extension to Any class, the object of classes written in Java was not been able to use these.\n//Java code public class Employee { private String firstName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @NonNull @Override public String toString() { return super.toString(); } } Now If Kotlin has added let function as an extension to Any class, the object of this Employee class couldn\u0026rsquo;t have used it.\nBut since the let function is an extension to Template class, this Employee class object can also use it.\n//Kotlin code val employee = Employee() employee.let { //do anything here } So to make these functions available for all the classes having any other superclass (like Object), Kotlin has added these functions as an extension to Template class. ","tags":["Kotlin"],"title":"Why let function is an Extension to Template class?"},{"categories":["Blog"],"date":"February 25, 2020","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-let-function/","section":"blogs","summary":"Kotlin has made our life very easy by providing features like extension functions, nullability check and much more. One such kind of really helpful feature is Scope functions. Once you understand what scope functions are, you will not able to resist yourself from using them.\nScope functions are nothing but the functions which define to the scope of the calling object. We can apply operations on that object within that scope and return the object itself from that scope function or we can even return the result of operation or operations from the scope function.\nThere are a few scope functions\nlet with run apply also To keep this article short and to the point, we will talk only about let in this article and all the use cases around it.\nlet scope function is used to apply operations on an object and finally return the lambda expression from that scope function. The return type can also be void.\nTo understand let function lets look at the implementation of let function first.\n/** * Calls the specified function [block] * with `this` value as its argument * and returns its result. * */ @kotlin.internal.InlineOnly public inline fun \u0026lt;T, R\u0026gt; T.let(block: (T) -\u0026gt; R): R { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return block(this) } let is an extension function to Template class which takes a lambda as a parameter, apply contract on it and ultimately return the execution of the lambda we passed as a parameter to it.\nThis clarifies a few things The return type of the let function is nothing but the last expression we returned from our passed lambda parameter. Since its an extension function to the Template class, it can be called on any object. Now let\u0026rsquo;s understand what is the contract. The contract is nothing but a contract applied to the passed lambda as a parameter.\n/** * Specifies the contract of a function. * * The contract description must be at the beginning of a function and have at least one effect. * * Only the top-level functions can have a contract for now. * * @param builder the lambda where the contract of a function is described with the help of the [ContractBuilder] members. * @ContractsDsl @ExperimentalContracts @InlineOnly @SinceKotlin(\u0026#34;1.3\u0026#34;) @Suppress(\u0026#34;UNUSED_PARAMETER\u0026#34;) public inline fun contract(builder: ContractBuilder.() -\u0026gt; Unit) { } This is exactly the same contract as to any other scope function. This superimposes some conditions on the lambda we passed as a parameter to the let function. What conditions it superimposed, we need to check the parameter of the contract\nAnd what contract applied in the let function ? /** * Specifies that the function parameter [lambda] is invoked in place. * * This contract specifies that: * 1. the function [lambda] can only be invoked during the call of the owner function, * and it won\u0026#39;t be invoked after that owner function call is completed; * 2. _(optionally)_ the function [lambda] is invoked the amount of times specified by the [kind] parameter, * see the [InvocationKind] enum for possible values. * * A function declaring the `callsInPlace` effect must be _inline_. * */ /* @sample samples.contracts.callsInPlaceAtMostOnceContract * @sample samples.contracts.callsInPlaceAtLeastOnceContract * @sample samples.contracts.callsInPlaceExactlyOnceContract * @sample samples.contracts.callsInPlaceUnknownContract */ @ContractsDsl public fun \u0026lt;R\u0026gt; callsInPlace(lambda: Function\u0026lt;R\u0026gt;, kind: InvocationKind = InvocationKind.UNKNOWN): CallsInPlace It superimposes 2 conditions\nThe lambda will be invoked only during owner function call and it won\u0026rsquo;t be called once the owner function is completed. The number of times this lambda function will be invoked (which is exactly once in our case) which is an enum. The above conditions are clear from there definition itself.\nSo basically, let function will be called only during the owner function will be called. called ONLY ONCE. called on the calling object. and will return the expression returned by the lambda passed to the let function. Now let\u0026rsquo;s look at the use cases The best use case of this let function is to avoid the null check. let function used with ?. ensures the execution only if the expression is non-null. You can read about the null safety in the Kotlin here.\nclass Employee { var firstName: String? = null var age: Int = 0 } val employee: Employee? = Employee() employee?.firstName = \u0026#34;Suneet\u0026#34; employee?.age = 27 employee?.let { println(it.age) } Please note that we can point to the calling object by using it. we can even use a local parameter for the calling object to avoid conflicts in the nested let or lambda function.\nemployee?.let { person -\u0026gt; person.firstName?.let { name -\u0026gt; println(name) } } Here the person and name are the named variable within the let function scope.\nIf the let lambda contains only a single expression, we can even use method reference (::) instead of lambda\nemployee?.firstName?.let (::println) Also, the let function can be used to invoke one or more functions on the result of the chain.\nvar list = mutableListOf(6, 1, 5, 2, 4, 3) list.filter { it % 2 == 0 }.sortedBy { it }.let { println(\u0026#34;Sorted even numbers are : $it\u0026#34;) } //this will print Sorted even numbers are : [2, 4, 6] If we want to return that object from let function, return without marking any return statement. In the below example, the sorted even numbers list will be returned.\nvar list = mutableListOf(6, 1, 5, 2, 4, 3) var sortedEvenList = list.filter { it % 2 == 0 }.sortedBy { it }.let { println(\u0026#34;Sorted even numbers are : $it\u0026#34;) it } Things to keep in mind about let, let uses the context as it or we can use a named parameter. let return the last expression of the lambda passed which can also be void. ","tags":["Kotlin"],"title":"Kotlin let function"},{"categories":["Blog"],"date":"December 2, 2019","permalink":"https://agrawalsuneet.github.io/blogs/inheritance-vs-extension-functions/","section":"blogs","summary":"We all know about inheritance which is there in the OOPs concept where one can extend a class and add functionality to it. In the new programming languages, there is something called as extension functions which can add a functionality to an existing class without extending it.\nSometimes we are confused about what to use when. To get help here, one needs to understand first what are these two and what are the benefits and limitations over the other. Once you understand the difference, it will be very easy to decide what to use.\nLet\u0026rsquo;s understand with code first what are both. I am going to explain using Kotlin language example but the concept is the same across all the languages.\nInheritance Inheritance is nothing but extending a class and adding functionality to it. You can add properties (variables) as well as functions in the extending class. You can access the variables of extending (Base) class if they are not private (protected or internal or public) can override them if they are not final (open variables) or you can override the functions also.\nopen class \u0026lt;b\u0026gt;Person\u0026lt;/b\u0026gt;(var firstName : String, protected var lastName : String) { open fun getFullDetails() : String { return \u0026#34;$firstName $lastName\u0026#34; } } class \u0026lt;b\u0026gt;Student\u0026lt;/b\u0026gt; : \u0026lt;b\u0026gt;Person\u0026lt;/b\u0026gt; { var rollNumber = 0 constructor(firstName : String, lastName: String, rollNumber : Int) : super (firstName, lastName){ this.rollNumber = rollNumber } override fun getFullDetails() : String { return \u0026#34;$firstName $lastName with Roll number as $rollNumber\u0026#34; } } And we can call it by using\nvar student = Student (\u0026#34;Suneet\u0026#34;, \u0026#34;Agrawal\u0026#34;, 12) println(student.getFullDetails()) Here we added a property i.e. rollNumber and override the function.\nNow let\u0026rsquo;s have a look at almost similar functionality using Extension functions.\nExtension Function Extension functions are the functions where you add a functionality to an existing class by just adding a function without extending the class and this will be resolved statically and all the objects of that class can use it.\nclass \u0026lt;b\u0026gt;Employee\u0026lt;/b\u0026gt;(var firstName : String, var lastName : String) { } fun Employee.getFullDetails() : String { return \u0026#34;$firstName $lastName\u0026#34; } We have a similar kind of class which is non open (final class). we added a function getFullDetails as an extension function to the employee class and we call the above function as\nvar emp = Employee(\u0026#34;Suneet\u0026#34;, \u0026#34;Agrawal\u0026#34;) println(emp.getFullDetails()) Now that we understand what is extension functions and what is an inheritance, let try to find out the difference which will make our life really easy while choosing what to use when.\nMerits of Extension functions Can add functionality to a final class also. The class need not be a non-final (open) class. Can add functionality without subclassing that means the object reference and the implementation can be of your base class. Limitations of Extension functions Can\u0026rsquo;t access the protected variables/properties or functions of your base class. Can\u0026rsquo;t add any new variable/properties in your extension functions. You can add a property by just writing getter and setter but only without backing field. So basically you can\u0026rsquo;t add a field in the base class. Merits of Inheritance Can add new properties, override functions (non-final) of the base class. Can access all protected variables and functions of the base class. Limitations of Inheritance Can\u0026rsquo;t extend a final class. I hope this made clear on what are the merits and demerits of extension functions and inheritance. Please note that the extension functions are resolved statically.\n","tags":["Kotlin"],"title":"Inheritance vs Extension functions"},{"categories":["Blog"],"date":"October 23, 2019","permalink":"https://agrawalsuneet.github.io/blogs/partition-kotlin/","section":"blogs","summary":"The collection is something which is used by almost everyone. It makes our life easy. List, Set and Map are the best examples of them. Even the programming language in which you are writing code provides you with a few basic operations that can be performed on those collections, But sometimes you need even more operations.\nRecently in one of my use case, the basic operations were not enough for me. My use case was very simple. I was having a list on which I need to perform an operation to segregate its items into two lists, one which agrees to some condition and the other which doesn’t.\nThe typical way to do this is to run a loop over the collection object and add an if condition inside and segregate the object.\nval list = listOf(1 , 2, 3, 4, 5) val evenList = mutableListOf\u0026lt;Int\u0026gt;() val oddList = mutableListOf\u0026lt;Int\u0026gt;() for(item in list){ if(item % 2 == 0){ evenList.add(item) } else { oddList.add(item) } } println(evenList) println(oddList) Kotlin has something inbuild, which can make your life easier. There is an operator caller partition() which can segregate the list into two lists, one with the items matching the condition and another one with the non-matching condition.\nval list = listOf(1 , 2, 3, 4, 5) val (even, odd) = list.partition { it % 2 == 0} println(even) println(odd) If you check the actual implementation of the partition function, this is actually the same.\n/** * Splits the original collection into pair of lists, * where *first* list contains elements for which [predicate] yielded `true`, * while *second* list contains elements for which [predicate] yielded `false`. */ public inline fun \u0026lt;T\u0026gt; Iterable\u0026lt;T\u0026gt;.partition (predicate: (T) -\u0026gt; Boolean): Pair\u0026lt;List\u0026lt;T\u0026gt;, List\u0026lt;T\u0026gt;\u0026gt; { val first = ArrayList\u0026lt;T\u0026gt;() val second = ArrayList\u0026lt;T\u0026gt;() for (element in this) { if (predicate(element)) { first.add(element) } else { second.add(element) } } return Pair(first, second) } There is no difference in the implementation but since its an inbuild inline function, you don’t have to write the entire iteration and condition check on your own. Please note that there is no difference in time or space complexity also.\nThe only reason I wrote about this as a blog is because I feel I am lazy and prefers to use all inbuild functions to write fewer lines of code. :) This was one of them.\n","tags":["Kotlin"],"title":"partition() : Kotlin"},{"categories":null,"date":"September 24, 2019","permalink":"https://agrawalsuneet.github.io/publicappearances/droidcon-greece-2019/","section":"publicappearances","summary":"","tags":null,"title":"Speaker at Droidcon Greece"},{"categories":null,"date":"September 19, 2019","permalink":"https://agrawalsuneet.github.io/publicappearances/droidcon-vienna-2019/","section":"publicappearances","summary":"","tags":null,"title":"Speaker at Droidcon Vienna"},{"categories":null,"date":"September 9, 2019","permalink":"https://agrawalsuneet.github.io/personalgamesandapps/jaipur-metro/","section":"personalgamesandapps","summary":"","tags":null,"title":"Jaipur Metro"},{"categories":null,"date":"September 9, 2019","permalink":"https://agrawalsuneet.github.io/publicappearances/droidcon-lisbon-2019/","section":"publicappearances","summary":"","tags":null,"title":"Speaker at Droidcon Lisbon"},{"categories":null,"date":"August 31, 2019","permalink":"https://agrawalsuneet.github.io/publicappearances/droidjam-bangalore-2019/","section":"publicappearances","summary":"","tags":null,"title":"Speaker at DroidJam Bangalore"},{"categories":null,"date":"August 24, 2019","permalink":"https://agrawalsuneet.github.io/personalgamesandapps/space-shooter/","section":"personalgamesandapps","summary":"","tags":null,"title":"SpaceShooter"},{"categories":null,"date":"August 24, 2019","permalink":"https://agrawalsuneet.github.io/publicappearances/mobileconf-2019/","section":"publicappearances","summary":"","tags":null,"title":"Speaker at MobileConf 2019"},{"categories":null,"date":"August 4, 2019","permalink":"https://agrawalsuneet.github.io/personalgamesandapps/basketball-3d/","section":"personalgamesandapps","summary":"","tags":null,"title":"Basketball 3D"},{"categories":["Slide"],"date":"August 4, 2019","permalink":"https://agrawalsuneet.github.io/slides/cut-your-apk-size-with-features-on-demand/","section":"slides","summary":" Do APK or app size matters? Does a user think about the APK size before downloading it? Does a user think about space, an app occupying on the phone? Is your App size is more than just a few MBs? What if we provide very basic functionality and let the user decide whether he wants the advanced or additional functionality or not?\nYes, The user thinks about the app size before downloading or updating an app which has a size larger than a few MBs. The user thinks about the data also over which he will be downloading or updating that app. He or she even think about how much space will it take on his or her device. In this fight of space in the device and size of the app, the apps having a smaller size and frequent utility wins the battle.\nWhat if we provide very basic functionality and let the user decide whether he wants the advanced or additional functionality or not. What if he or she can download only the features he needs on demand and keep the app compact.\nGoogle new feature of dynamic delivery enables us to deliver the features on demand. This helps us to reduce the size of APK and even enables the user to choose what features he needs. From a developers perspective, this is very easy to implement and maintain.\nEven we (Sharechat) were also at the same state where the size of APK was an issue with the new set of features we were trying to implement. Google Dynamic delivery came to the rescue.\nWhat is the dynamic delivery? How can we reduce the APK size with it? How it can help a user? How to implement it in Android? How difficult is it to implement in the existing code base? How will it look to the user in the app? Well, let\u0026rsquo;s get all these questions answered in the presentation below with our experiences and challenges we faced.\nThis topic was presented at various Android confrences listed here.\n","tags":["Android"],"title":"Cut your APK Size with features on demand"},{"categories":null,"date":"August 4, 2019","permalink":"https://agrawalsuneet.github.io/publicappearances/gdg-devfest-kolkata-2019/","section":"publicappearances","summary":"","tags":null,"title":"Speaker at GDG Devfest Kolkata"},{"categories":["Blog"],"date":"May 28, 2019","permalink":"https://agrawalsuneet.github.io/blogs/native-android-image-sharing-in-unity-using-fileprovider/","section":"blogs","summary":"While implementing native sharing using my previous post, Native Android image sharing in Unity we saw an exception android.os.FileUriExposedException in Android 8 (Oreo) and above.\nSince Google changed the sharing way using FileProvider to make it more secure, we can not share the file object directly to any other Application. We need to use the FileProvider and grant read URI permission to make it accessible for any other app.\nIn this blog, will guide step by step to enable image sharing to any other app using FileProvider. After this, you can share your screenshots or image to any other apps on above Android 8 (Oreo) also. Please stay with me as it\u0026rsquo;s going to be a long journey.\nBut before that, I would suggest to please go through my last blogs that will give an insight into what we are trying to achieve.\nIf you have not read the previous blogs, I would strongly recommend to read them first. You can read them on the links below.\nNative Android in Unity Native Android text sharing in Unity Native Android image sharing in Unity To use file provider in Unity and share a screenshot/image, we need to follow below steps.\nCreate a project and separate module in Native Android using Android Studio. Define paths in xml file in native android. Define Provider in Android manifest file. Export it as an Android archive file (.aar) from Android Studio. Enable Gradle dependency in Unity project. Add Support dependency in the gradle file. Change sharing intent code in the C# file. We can skip the first 4 steps and can use “.aar” file generated by me (which I will share) also but to give everyone an insight about what is happening exactly,\nLet’s go step by step.\n1. Create a project and separate module in Native Android using Android Studio Since putting a raw Android XML is not allowed in Unity, we need a separate Android module containing our code and export it as an aar file to use it in Unity. To create the same we need Android studio. I am not going to follow on how to download and setup android studio. You can Google it and set it up.\nCreate a new project in Android studio.\nSelect the minimum API level same as your unity project and fill all remaining fields. These fields really don’t matter as we are going to create a separate library in this project. Click on finish.\nCreate new “Android Library Module” in the same project by clicking File \u0026gt; New \u0026gt; New Module.\nName the library and click finish.\nOnce this is done, we can remove the unnecessary dependencies and folders like test and androidTest folder. We can also remove the string.xml file. We can even remove the testing dependency from build.gradle of our library.\n//testInstrumentationRunner // \u0026#34;android.support.test.runner.AndroidJUnitRunner\u0026#34; and //testImplementation \u0026#39;junit:junit:4.12\u0026#39; //androidTestImplementation \u0026#39;com.android.support.test:runner:1.0.2\u0026#39; //androidTestImplementation // \u0026#39;com.android.support.test.espresso:espresso-core:3.0.2\u0026#39; Please note that we need appcompat support library. The final build.gradle will be\napply plugin: \u0026#39;com.android.library\u0026#39; android { compileSdkVersion 28 defaultConfig { minSdkVersion 14 targetSdkVersion 28 versionCode 1 versionName \u0026#34;1.0\u0026#34; testInstrumentationRunner \u0026#34;android.support.test.runner.AndroidJUnitRunner\u0026#34; } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile(\u0026#39;proguard-android-optimize.txt\u0026#39;), \u0026#39;proguard-rules.pro\u0026#39; } } } dependencies { implementation fileTree(dir: \u0026#39;libs\u0026#39;, include: [\u0026#39;*.jar\u0026#39;]) implementation \u0026#39;com.android.support:appcompat-v7:28.0.0\u0026#39; } 2. Define paths in xml file in native android Create a new XML resource file with name provider_paths.xml in our library.\nreplace the below code in the created provider_paths.xml file and save it.\n\u0026lt;?xml version=\u0026#34;1.0\u0026#34; encoding=\u0026#34;utf-8\u0026#34;? \u0026gt; \u0026lt;paths xmlns:android=\u0026#34;http://schemas.android.com/apk/res/android\u0026#34; \u0026gt; \u0026lt;external-path name=\u0026#34;external_files\u0026#34; path=\u0026#34;.\u0026#34;/ \u0026gt; \u0026lt;/paths \u0026gt; 3. Define Provider in Android manifest file. Define Provider in the manifest.xml file of the library.\n\u0026lt;manifest xmlns:android=\u0026#34;http://schemas.android.com/apk/res/android\u0026#34; package=\u0026#34;com.agrawalsuneet.unitysharing\u0026#34; \u0026gt; \u0026lt;uses-permission android:name=\u0026#34;android.permission.WRITE_EXTERNAL_STORAGE\u0026#34; / \u0026gt; \u0026lt;application \u0026gt; \u0026lt;provider android:name=\u0026#34;android.support.v4.content.FileProvider\u0026#34; android:authorities=\u0026#34;${applicationId}.provider\u0026#34; android:exported=\u0026#34;false\u0026#34; android:grantUriPermissions=\u0026#34;true\u0026#34; \u0026gt; \u0026lt;meta-data android:name=\u0026#34;android.support.FILE_PROVIDER_PATHS\u0026#34; android:resource=\u0026#34;@xml/provider_paths\u0026#34; / \u0026gt; \u0026lt;/provider \u0026gt; \u0026lt;/application \u0026gt; \u0026lt;/manifest \u0026gt; Please note that we are adding write external storage permission here only but you can add it in unity also. I added here so that we don’t miss it.\n4. Export it as an Android archive file (.aar) from Android Studio To export the aar file out of our library, run the below command in the terminal on our root folder of android project.\n./gradlew assembleRelease This will generate a release android archive (.aar) file in unitysharing/build/outputs/aar/ folder.\n5. Enable Gradle dependency in Unity project I am assuming here that everyone who is here already has a unity project and knows at least basics of unity and the folder structures in unity.\nCopy the aar file generate from Android studio and place it in /Assets/Plugins/Android/ folder.\nCreate Plugins and Android folder if not there and inside the Android folder put the aar file.\nPlease note that I have changed the name of the aar file from unitysharing-release.aar to unitysharing.aar but it really doesn’t matter. The name of the file really does not make any difference.\nNow if you remember, we added a dependency of appcompat support library in our android library’s build.gradle file. Since the FileProvider is defined in that support library of Android only, we need the same in our unity project also. To add that dependency in our unity project we need to enable the custom build.gradle file for our unity project.\nOpen File \u0026gt; Build Settings in Unity.\nSwitch platform to Android.\nOpen Player Settings and navigate to the Publishing Settings section.\nCheck the checkbox next to “Custom Gradle Template”. This will generate a “mainTemplate.gradle” file in the same Assets/Plugins/Android folder.\n6. Add Support dependency in the gradle file. Open the newly created “mainTemplate.gradle” file in any editor.\nAdd the below line at the bottom of that file.\ndependencies { implementation fileTree(include: [\u0026#39;*.jar\u0026#39;], dir: \u0026#39;libs\u0026#39;) implementation \u0026#39;com.android.support:appcompat-v7:28.0.0\u0026#39; } Please note if you already using the custom gradle file, add only appcompat dependency into your dependencies section. Please do not touch the dependencies block above android block. That dependency block is for root project similar to native android.\nPlease be careful with this file otherwise the project will not compile. Also, do not touch anything which is auto-generated. My final mainTemplate.gradle file will look like below.\n7. Change sharing intent code in the C# file This is the final change. I am assuming that whoever is here had already read my previous post [Native Android image sharing in Unity(/blogs/native-android-image-sharing-in-unity/) and is aware of the basic intent object we created to share.\nSince last time we were creating the URI object by parsing the File object which is not allowed now, we will create the URI object using FileProvider.\n//old code which is not allowed in Android 8 or above //create image URI to add it to the intent //AndroidJavaClass uriClass = new AndroidJavaClass (\u0026#34;android.net.Uri\u0026#34;); //AndroidJavaObject uriObject = //uriClass.CallStatic \u0026lt;AndroidJavaObject \u0026gt;(\u0026#34;parse\u0026#34;, \u0026#34;file://\u0026#34; // + screenShotPath); //create file object of the screenshot captured AndroidJavaObject fileObject = new AndroidJavaObject(\u0026#34;java.io.File\u0026#34;, screenShotPath); //create FileProvider class object AndroidJavaClass fileProviderClass = new AndroidJavaClass(\u0026#34;android.support.v4.content.FileProvider\u0026#34;); object[] providerParams = new object[3]; providerParams[0] = currentActivity; providerParams[1] = \u0026#34;com.agrawalsuneet.unityclient.provider\u0026#34;; providerParams[2] = fileObject; //instead of parsing the uri, //will get the uri from file using FileProvider AndroidJavaObject uriObject = fileProviderClass.CallStatic \u0026lt;AndroidJavaObject \u0026gt;(\u0026#34;getUriForFile\u0026#34;, providerParams); Please note that the object passed at position 1 in the array should be your \u0026lt;application id\u0026gt;.provider\nThis is the same as what we defined in the manifest file of the Android library.\nandroid:authorities=\u0026#34;${applicationId}.provider\u0026#34; Crosscheck the spelling correctly.\nAdditionally, add the granting permission to read the URI as a flag to the intent.\n//additionally grant permission to read the uri intentObject.Call \u0026lt;AndroidJavaObject \u0026gt;(\u0026#34;addFlags\u0026#34;, intentClass.GetStatic \u0026lt;int \u0026gt;(\u0026#34;FLAG_GRANT_READ_URI_PERMISSION\u0026#34;) ); The final script will look like below.\nConnect this script to any game object and assign the Button and we are done.\nI have uploaded all the code (Android and Unity both) into a public Github repository UnitySharingCenter\nI have also kept my “aar” public which can be directly used in any Unity project and can skip the above 4 steps. Please find the aar at UnitySharingCenter/Releases\nThank you for your patience. Please write in comments sections if it worked fine for you or not.\n","tags":["Unity","CSharp"],"title":"Native Android image sharing in Unity using FileProvider"},{"categories":["Blog"],"date":"May 10, 2019","permalink":"https://agrawalsuneet.github.io/blogs/takeif-and-takeunless-kotlin/","section":"blogs","summary":"Ever thought of chaining an if condition?\nWhat if we can chain the if condition also and moves or executes the next code in the chain only if the condition is true?\nKotlin has something very interesting to achieve the same.\nWe can use takeIf and takeUnless to achieve the same. As clear from the name itself, takeIf will proceed in the chain only if the condition inside is true whereas takeUnless is the counter of takeIf and will proceed only if the provided condition is false.\ntakeIf takeIf is a filtering function for a single object whereas takeUnless is a counter of takeIf.\nLet’s take an example to understand the same.\nfun getLatency():Int { return (0..30).random() } val networkLatency = getLatency() println(networkLatency) if (networkLatency \u0026lt; 20){ // join the game println(\u0026#34;can join the game with latency $networkLatency\u0026#34;) } In the above example, we need to check the latency of the network and join the game only it is less than 20. Now to achieve the same we need to put an if condition, the reason I need to introduce a new variable networkLatency is because I need to pass it to the inner function also.\nNow to achieve the same within single chaining, I can use takeIf.\ngetLatency()?.takeIf{ it \u0026lt; 20} ?.let{ println(\u0026#34;can join the game with latency $it\u0026#34;) } Please note that both takeIf and takeUnless returns null if the condition is not satisfied, so to chain it further we need to use the safe call or null check.\ntakeUnless Let\u0026rsquo;s take an example of takeUnless.\ngetLatency()?.takeUnless{ it \u0026lt; 20} ?.let{ println(\u0026#34;warning : high latency $it\u0026#34;) } In this case, this will only proceed when the latency is more than 20 ie not less than 20, and will chain it further. Also, if the condition is false that means if the latency is less than 20, it will return null so we need to use the safe call or null check.\n","tags":["Kotlin"],"title":"takeIf and takeUnless : Kotlin"},{"categories":["Blog"],"date":"April 5, 2019","permalink":"https://agrawalsuneet.github.io/blogs/inline-function-kotlin/","section":"blogs","summary":"What is inlining? Inlining is basically requesting the compiler to copy the (inlined) code at the calling place.\nWhy it is required? When a program is executed and a function is called, CPU stores the memory address of the instruction following the function call, copies the arguments of the function into a stack and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register and returns control to the calling function.\nIn Kotlin, the higher order functions or lambda expressions, all stored as an object which takes some memory and might increase the memory overhead. Sometimes, the function does a very basic functionality that passing the control is not even worth but as it (the function) is being used at multiple places, we need to create a separate function. To reduce the memory overhead of such functions we can use the inline keyword which ultimately requests the CPU to not allocate any memory for the function and simply copy the body of that function at the calling place.\nLet’s take an example. suppose we have a function which simply checks if the first argument is a multiple of the second argument and returns a boolean.\nfun isMultipleOf (number: Int, multipleOf : Int): Boolean{ return number % multipleOf == 0 } Now to use this function as a higher order function,\nfun \u0026lt;T\u0026gt; ArrayList\u0026lt;T\u0026gt;.filterOnCondition(condition: (T) -\u0026gt; Boolean): ArrayList\u0026lt;T\u0026gt;{ val result = arrayListOf\u0026lt;T\u0026gt;() for (item in this){ if (condition(item)){ result.add(item) } } return result } var list = arrayListOf\u0026lt;Int\u0026gt;() for (number in 1..10){ list.add(number) } val resultList = list.filterOnCondition { isMultipleOf(it, 5) } print(resultList) In the above example, the functionality of the isMultipleOf is so small that it can be copied but as it can be used at multiple places, we created it as a separate function. As this function is passed as an argument to filterOnCondition function, CPU will assign it to some object which will take some memory. Also, for every item in the list, the CPU will jump to the memory address of isMultipleOf function and will pass back to result.\nTo prevent this, we can make the isMultipleOf function as inline which will as the compiler to copy it to the calling place which will prevent the memory allocation of the function and jumping of the CPU at runtime.\ninline fun isMultipleOf (number: Int, multipleOf : Int): Boolean { return number % multipleOf == 0 } The functionality will remain the same.\nThings to keep in mind We will lose access to any private variable or function of the class inside the inline function. So it’s better to make functions inline which are very generic and don’t use a class level variable or function to achieve their functionality. private var localVariable : Int = 8 inline fun isMultipleOf (number: Int, multipleOf : Int): Boolean { print(localVariable) //compilation error return number % multipleOf == 0 } The above code will show compilation error\n\u0026lt;e\u0026gt;Public-API inline function cannot access non-public-API \u0026#39;private var localVariable\u0026lt;/e\u0026gt; Which is clear in itself.\nDo not inline for bigger functions as it degrades the performance. ","tags":["Kotlin"],"title":"Inline function : Kotlin"},{"categories":["Blog"],"date":"March 29, 2019","permalink":"https://agrawalsuneet.github.io/blogs/mutating-in-swift/","section":"blogs","summary":"As we all know, Classes are reference type whereas Structures and Enumerations are of a value type in swift. What does that mean is that a class object shares a single instance of the object and passes the same reference if passed to any function or new object whereas the value type is the one which creates a copy of it and passes only the value.\nIf we try to change any variable inside a class it’s straight forward.\nclass Employee { var name : String var teamName : String init(name: String, teamName: String) { self.name = name self.teamName = teamName } func changeTeam(newTeamName : String){ self.teamName = newTeamName } } var emp1 = Employee(name : \u0026#34;Suneet\u0026#34;, teamName:\u0026#34;Engineering\u0026#34;) print(emp1.teamName) //Engineering emp1.changeTeam(newTeamName : \u0026#34;Product\u0026#34;) print(emp1.teamName) //Product Whereas if you try to do the same in any value type, it will show us a compilation error,\nstruct Employee { var name : String var teamName : String init(name: String, teamName: String) { self.name = name self.teamName = teamName } func changeTeam(newTeamName : String){ self.teamName = newTeamName \u0026lt;e\u0026gt;//cannot assign to property: \u0026#39;self\u0026#39; is immutable\u0026lt;/e\u0026gt; } } It will show us the below error\n//error: cannot assign to property: \u0026#39;self\u0026#39; is immutable It clearly states that adding mutating keyword to any function in value type can enable them to modify the variable. Internally when we try to mutate the value type, it does not mutate its value but it mutates the variable holding that value.\nstruct Employee { var name : String var teamName : String init(name: String, teamName: String) { self.name = name self.teamName = teamName } mutating func changeTeam(newTeamName : String){ self.teamName = newTeamName } } var emp1 = Employee(name : \u0026#34;Suneet\u0026#34;, teamName:\u0026#34;Engineering\u0026#34;) print(emp1.teamName) //Engineering emp1.changeTeam(newTeamName : \u0026#34;Product\u0026#34;) print(emp1.teamName) //Product Not only enum or struct but there are other data types also which are of value type.\nenum struct Int Double String Array Dictionary Set Tuple Whereas the below ones of reference type\nFunctions Closures Class ","tags":["Swift"],"title":"mutating in Swift"},{"categories":["Blog"],"date":"March 1, 2019","permalink":"https://agrawalsuneet.github.io/blogs/inout-in-swift/","section":"blogs","summary":"Recently, while working with swift I came up with a use case where I need to modify the variable passed as an argument to a function. Eventually, all the variables passed to a function are of an immutable type which cannot be changed which is similar to a let variable. If it’s a class object, you cannot create a new object but you can manipulate the properties of that class object or you can call any function with that object.\nclass Employee { var name : String var age : Int init(name: String, age: Int){ self.name = name self.age = age } } func changeEmployeeData(emp : Employee){ employee.name = \u0026#34;Suneet\u0026#34; employee.age = 25 } let employee = Employee(name: \u0026#34;Random\u0026#34;, age : 10) print(employee.name) //Random print(employee.age) //10 changeEmployeeData(emp : employee) print(employee.name) //Suneet print(employee.age) //25 Now the problem occurs when your argument is of primitive data type, you simply can’t change the value.\nvar variable: Int = 1 func changeNumber (num: Int) { num = 2 print(num) } changeNumber(num : variable) It will show the error cannot assign to value: ‘num’ is a ‘let’ constant which is self-explanatory.\nWe can’t modify the parameter passed as an argument as those are of let type.\nNow, what if I want to modify this value? inout to the rescue.\nYou can use inout where it passes the parameter as a reference.\nvar variable: Int = 1 func changeNumber (num:inout Int) { num = 2 print(num) // 2 } changeNumber(num : \u0026amp;variable) You need to add inout before the datatype of the variable and an \u0026amp; while passing the parameter.\nComing back to our previous example where we just changed the properties value, what if we want to assign it a new object itself.\nclass Employee { var name : String var age : Int init(name: String, age: Int){ self.name = name self.age = age } } func changeEmployeeData(emp : Employee){ emp = Employee(name: “Suneet”, age: 25) } var employee = Employee(name: “Random”, age : 10) print(employee.name) print(employee.age) changeEmployeeData(emp : employee) print(employee.name) print(employee.age) This will show us the same compilation error cannot assign to value: ‘emp’ is a ‘let’ constant.\nInstead, we can use the inout after which we can modify the object.\nfunc changeEmployeeData(emp :inout Employee){ emp = Employee(name: “Suneet”, age: 25) } var employee = Employee(name: “Random”, age : 10) print(employee.name) //Random print(employee.age) //10 changeEmployeeData(emp : \u0026amp;employee) print(employee.name) //Suneet print(employee.age) //25 The only thing to keep in mind while using the inout is, as we pass the address of the variable/object, it modifies the actual object also.\n","tags":["Swift"],"title":"‘inout’ in Swift"},{"categories":["Blog"],"date":"February 7, 2019","permalink":"https://agrawalsuneet.github.io/blogs/qualified-this-in-kotlin/","section":"blogs","summary":"The only thing we learnt about this pointer in other languages is “this is an implicit pointer which points to the calling object”. As clear from the definition, it points to the object which calls the respective function or property.\nNow the real problem arises when we have an inner class or anonymous interface implementation. We lose the reference of the outer class. Let me give you an example.\n//java code //extending Android View class public class CustomView extends View { public CustomView(Context context) { super(context); getViewTreeObserver() .addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { //this. //will not get the reference of //CustomView here } }); } } In the above code, we extended the class from View class which has a property of class ViewTreeObserver. ViewTreeObserver class has two functions addOnGlobalLayoutListener and removeGlobalOnLayoutListener which takes OnGlobalLayoutListener Interface reference object.\nNow when we implemented the anonymous object of OnGlobalLayoutListener for the same, we can’t get the reference of my CustomView class inside the overridden method. Now If we want to call any function of CustomView from inside the overridden method, we can’t.\nTo do the same we need to define another final variable and use it.\n//java code //extending Android View class public class CustomView extends View { public CustomView(Context context) { super(context); final CustomView view = this; getViewTreeObserver() .addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { view.doSomething(); } }); } private void doSomething(){ } } Now to make our life easy, Kotlin has something called qualified ‘this’.\nLet me give you the equivalent code in Kotlin.\nclass CustomView : View { constructor(context: Context) : super(context) { viewTreeObserver .addOnGlobalLayoutListener ( object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { this@CustomView.doSomething() } }) } private fun doSomething() { } } or if you want to use a lambda\nclass CustomView : View { constructor(context: Context) : super(context) { viewTreeObserver .addOnGlobalLayoutListener { this@CustomView.doSomething() } } private fun doSomething() { } } as you can see we can even reference the this pointer using @ followed by the scope of that this pointer.\nLet\u0026rsquo;s take some other example\nclass OuterClass { inner class InnerClass{ fun Int.intExtensionFunction(){ val outerThis = this@OuterClass val innerThis = this@InnerClass val intExtThis = this@intExtensionFunction val currentThis = this // int receiver, which will be an int val funLiteral = lambda@ fun String.() { val funLiteralThis = this // funLiteral\u0026#39;s receiver which will be a string } val funLiteral2 = { string: String -\u0026gt; val funLiteral2This = this //since this lambada doesn\u0026#39;t have any receiver, //this will be an int (the extension fun reference) } } } } We can use any reference inside the inner class or even inner function based on our use case.\nThings to remember, In a member of a Class, this refers to the current object of that class. In an extension function or a function literal with the receiver, this denotes the receiver parameter that is passed on the left-hand side of a dot. If this has no qualifiers, it refers to the innermost enclosing scope. No need to define any final object to use any this reference. ","tags":["Kotlin"],"title":"Qualified ‘this’ in Kotlin"},{"categories":["Blog"],"date":"December 23, 2018","permalink":"https://agrawalsuneet.github.io/blogs/type-aliases-in-kotlin/","section":"blogs","summary":"Life is painful when you have two or more classes with the same name but different package name and you have to use them both in the same place.\nOnly one import can be added and the other one needs to be referenced by its complete package name dot class name. Every time you use the second class name, you need to use it by the entire package name of that class.\nKotlin has a better way to handle this case. It provides you type aliasing which basically provides an alternative name for the class.\ntypealias DemoCustomView = com.agrawalsuneet.demoapp.common.customviews.View In the above example, we aliased the View class which is in a specific package (com.agrawalsuneet.demoapp.common.customviews). Now we can directly use our View class using DemoCustomView and it will not conflict with android.view.View class.\nval demoView = DemoCustomView(context) the above code will do exactly the same as\nval demoView = com.agrawalsuneet.demoapp.common.customviews.View(context) You can define this typealias in any Kotlin file within the project but outside the class. You can not define the typealias inside any class as nested and local type aliases are not supported.\nMost of the time, it’s useful to shrink collection types.\ntypealias MapIntToList = HashMap\u0026lt;Int, List\u0026lt;String\u0026gt;\u0026gt; and use them directly as\nval map = MapIntToList() You can typealias to Template type also.\ntypealias MapIntToTemplate\u0026lt;T\u0026gt; = HashMap\u0026lt;Int, T\u0026gt; //and then to use it val stringMap = MapIntToTemplate\u0026lt;String\u0026gt;() val mapOfLists = MapIntToTemplate\u0026lt;List\u0026lt;Int\u0026gt;\u0026gt;() It’s useful to typealise the inner classes or interfaces.\nclass DemoClass { interface ViewHolderCallback inner class CustomViewHolder } typealias ViewHolderCallbackInner = com.agrawalsuneet.demoapp.common.DemoClass.ViewHolderCallback typealias CustomViewHolderInner = com.agrawalsuneet.demoapp.common.DemoClass.CustomViewHolder //another example typealias AndroidColors = android.R.color typealias ProjectColors = R.color ContextCompat.getColor(this, ProjectColors.colorPrimary) ContextCompat.getColor(this, AndroidColors.black) You can even provide different aliases for function types.\ntypealias Conditional\u0026lt;T\u0026gt; = (T) -\u0026gt; Boolean val oddFilter: Conditional\u0026lt;Int\u0026gt; = { it % 2 == 1 } print(listOf(1, 2, 3, 4).filter(oddFilter)) //or val fourDigitFilter : Conditional\u0026lt;String\u0026gt; = { it.length == 4} print(listOf(\u0026#34;abc\u0026#34;, \u0026#34;abcd\u0026#34;, \u0026#34;abcde\u0026#34;).filter(fourDigitFilter)) ","tags":["Kotlin"],"title":"Type Aliases in Kotlin"},{"categories":["Blog"],"date":"October 26, 2018","permalink":"https://agrawalsuneet.github.io/blogs/extensions-in-kotlin/","section":"blogs","summary":"Have you ever felt some useful functionality missing in an existing class?\nThe class could be in the libraries provided by language also.\n“Yes”\nWhat exactly you do to add that functionality in the class?\n“Extend the class and add the method and then use my own extended class”\nIf so, Kotlin extensions can definitely make your life easier.\nKotlin provides the ability to extend a class with new functionality without having to inherit from the class or use any type of design pattern such as Decorator. This is done using a special declaration called extensions. These extensions basically add some functionality in an existing class without extending the class.\nAnd how do we use it? I will explain this but before that, keep in mind that Kotlin supports both, extension functions and extension properties (Without backing field). Let’s understand them one by one.\nExtension Functions To declare an extension function, we need to prefix its name with a receiver type, i.e. the type being extended or the class name.\nLet’s say we want to add a function in the List Interface implementation which returns the element at the mid position of the list.\nfun \u0026lt;T\u0026gt; List\u0026lt;T\u0026gt;.midElement(): T { if (isEmpty()) throw NoSuchElementException(\u0026#34;List is empty.\u0026#34;) return this[size / 2] } //to call this method var list = listOf\u0026lt;Int\u0026gt;(1, 2, 3, 4, 5) var mid = list.midElement() //or var arrayList = arrayListOf(5, 4, 3, 2, 1) var mid = arrayList.midElement() So what we are doing here? We are adding a method named midElement in the List implementation which returns us the element at the mid position of the list. This method throws NoSuchElementException if the list is empty.\nLater this midElement method can be called with any normal List object.\nLet’s take another example of our very favorite Toast class in Android.\nToast class is used to show a message at the bottom half of the screen in Android for a long or short duration.\nThe native code to show a Toast in Android is\nToast.makeText(this, “Hello”, Toast.LENGTH_SHORT).show() The above code calls a static method makeText of Toast class with three parameters (reference of the current Context class, the CharSequence to be displayed and the Int duration for which the toast to be shown). The static method returns the Toast class object to which we call the show method.\nNow to make the call easy to this Toast from any class which extends the Context class directly or indirectly, we can create an extension method of Context class which will do the exact same.\nfun Context.showToast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, text, duration).show() } //to call this method from any context extending class showToast(\u0026#34;Hello\u0026#34;) How are extensions resolved? Statically.\nExtensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.\nThe extension functions dispatched statically. That means the extension function which will be called is determined by the type of the expression on which the function is invoked, not by the type of the result of evaluating that expression at runtime. In short, they are not virtual by receiver type.\nLet me explain. Let’s say we have two classes, one extending other and both have the same extension functions with same name and signature.\nopen class BaseClass class DerivedClass : BaseClass() fun BaseClass.someMethod(){ print(\u0026#34;BaseClass.someMethod\u0026#34;) } fun DerivedClass.someMethod(){ print(\u0026#34;DerivedClass.someMethod\u0026#34;) } Now if we try to call the someMethod with BaseClass object but the actual reference we pass to it will be DerivedClass reference,\nfun printMessage(base : BaseClass){ base.someMethod() } //actual call printMessage(DerivedClass()) This will print BaseClass.someMethod\nBut why? I passed the DerivedClass reference.\nBecause the extension function being called depends only on the declared type of the parameter base in printMessage method, which is the BaseClass class. This is different from runtime polymorphism as here it is resolved statically but not at the runtime.\nWhat if my class has the same method with the same signature that we are adding as an extension function?\nThe compiler will call the method declared in the class but not the extension function.\nclass BaseClass{ fun someMethod(){ print(\u0026#34;I am the actual someMethod\u0026#34;) } } fun BaseClass.someMethod(){ print(\u0026#34;I am the extension function\u0026#34;) } //to call this method BaseClass().someMethod() This will call the someMethod which s defined in BaseClass and will print\nI am the actual someMethod\nNullable Receiver The extensions can be defined with a nullable receiver type also. These extension function can be called on a nullable object variable.\nLet’s take an example of toString method.\nfun Any?.toString(): String { if (this == null) return \u0026#34;null\u0026#34; // after the null check, // \u0026#39;this\u0026#39; is autocast to a non-null type, // so the toString() below // resolves to the member function of the Any class return toString() } // not the above method can be call on a nullable variable also var nullableVariable : Any? = null nullableVariable.toString() Extension Properties Similarly to functions, we can add extension properties also.\nval \u0026lt;T\u0026gt; List\u0026lt;T\u0026gt;.midIndex: Int get() = if (size == 0) 0 else size / 2 Since extensions do not actually insert members into classes, there’s no efficient way for an extension property to have a backing field. This is why initializers are not allowed for extension properties. Their behavior can only be defined by explicitly providing getters/setters.\nclass BaseClass{ } var BaseClass.index : Int = 10 \u0026lt;e\u0026gt;//compile error\u0026lt;/e\u0026gt; //Extension property cannot be initialized //because it has no backing field Companion Object Extension We can also define extension functions and properties for the Companion object.\nclass BaseClass { companion object { } } fun BaseClass.Companion.companionMethod(){ } //to call this method BaseClass.companionMethod() Scope of Extensions Most of the time we define extensions on the top level, i.e. directly under packages.\npackage com.example.extension fun BaseClass.extensionFunction(){ } //and use it with import com.example.extension.extensionFunction // importing all extensions by name \u0026#34;extensionFunction\u0026#34; // or import com.example.extension.* // importing everything from \u0026#34;com.example.extension\u0026#34; fun usage(base: BaseClass) { base.extensionFunction() } but if you want to declare an extension function as a member of the other class we have some rules to follow which I will explain in another blog.\nRead more about extension functions on the below links.\nKotlin Extension Property How extension functions resolved? Inheritance vs Extension functions ","tags":["Kotlin"],"title":"Extensions in Kotlin"},{"categories":["Blog"],"date":"October 13, 2018","permalink":"https://agrawalsuneet.github.io/blogs/variable-number-of-arguments-vararg-kotlin/","section":"blogs","summary":"Sometimes we need a function where we can pass n number of parameters, and the value of n can be decided at runtime. Kotlin provides us to achieve the same by defining a parameter of a function as vararg. We can pass n number of parameters to a vararg variable of the defined datatype or even of a generic type.\nVariables Let me give you an example.\nWe need a function which takes n number as inputs and returns the average of all the inputs. If the size of n variables is not fixed, we usually convert it into an array or list and pass it to function.\nfun getAverage(numbersList: List\u0026lt;Int\u0026gt;): Float { var sum = 0.0f for (item in numbersList) { sum += item } return (sum / numbersList.size) } val arrayList = arrayListOf(1, 2, 3, 4) val result = getAverage(arrayList) Now, what if the function itself takes n inputs and we don’t need to convert it into an array.\nfun getAverage(\u0026lt;b\u0026gt;vararg\u0026lt;/b\u0026gt; input: Int): Float { var sum = 0.0f for (item in input) { sum += item } return (sum / input.size) } val result1 = getAverage(1, 2, 3) val result2 = getAverage(1, 2, 3, 4, 5) We can pass n number of inputs to the same function and can get the result back. Inside the function, the parameter is available as an Array object and we can perform all normal array operations on it.\nWe can even use Template type for vararg.\nfun \u0026amp;lt;T\u0026amp;gt; asList(\u0026lt;b\u0026gt;vararg\u0026lt;/b\u0026gt; input: T): List\u0026amp;lt;T\u0026amp;gt; { val result = ArrayList\u0026amp;lt;T\u0026amp;gt;() for (item in input) // input is an Array result.add(item) return result } Only one parameter may be marked as vararg. If a vararg parameter is not the last one in the list, values for the following parameters can be passed using the named argument syntax, or if the parameter has a function type, the value can be passed by passing a lambda outside parentheses.\nWe can even pass all the elements of an array along with other arguments to a vararg variable. We can use the spread (*) operator to do the same.\nfun getAverage(\u0026lt;b\u0026gt;vararg\u0026lt;/b\u0026gt; input: Int): Float { var sum = 0.0f for (item in input) { sum += item } return (sum / input.size) } val array = intArrayOf(1, 2, 3, 4) val result = getAverage(1, 2, 3, *array) ","tags":["Kotlin"],"title":"Variable number of arguments (vararg) : Kotlin"},{"categories":["Blog"],"date":"October 6, 2018","permalink":"https://agrawalsuneet.github.io/blogs/object-expression-in-kotlin/","section":"blogs","summary":"Sometimes we need to create an object of some class with slight modification, without explicitly declaring a new subclass for it. Java handles this case with anonymous inner classes. Kotlin uses object expression to achieve the same functionality.\nWe can even create an object expression for an interface or abstract class by just implementing their abstract methods. This functionality is called an anonymous interface implementation or anonymous abstract class implementation.\nLet’s understand with examples\nWe have a class AClass having someFunction in it. We want to pass AClass object to achieve some other functionality but at the same time, we want to override the default functionality of someFunction. Ideally, this can be done by creating another class extending AClass and overriding the someFunction method and then pass the object of extending class. But we can achieve the same using an anonymous inner class in Java.\n//Java code public class AClass { public void someFunction(){ System.out.println(\u0026#34;SomeClass : some Function\u0026#34;); } } public class UsageClass { public void useSomeClass(AClass someClassObj){ someClassObj.someFunction(); } } Now to use the method in UsageClass,\n//Java code UsageClass usageClass = new UsageClass(); usageClass.useSomeClass(new AClass(){ @Override public void someFunction() { super.someFunction(); System.out.println(\u0026#34;UsageClass : overridden some Function\u0026#34;); } }); We created an object of AClass and passed it to useSomeClass method also we overridden the functionality of somefunction without extending the class.\nThe same can be achieved in Kotlin using object expression.\n//Kotlin code open class AClass { open fun someFunction() { println(\u0026#34;SomeClass : some Function\u0026#34;) } } class UsageClass { fun useSomeClass(someClassObj: AClass) { someClassObj.someFunction() } } Now to use the method in UsageClass,\n//Kotlin code val usageClass = UsageClass() usageClass.useSomeClass(object : AClass() { override fun someFunction() { super.someFunction() println(\u0026#34;UsageClass : overridden some Function\u0026#34;) } }) Same can be possible in the case of anonymous interface implementation or anonymous abstract class implementation also.\nLet’s have a look.\n//Java code public abstract class AAbstractClass { abstract void doSomething(); public void iAmDoingSomething() { System.out.println(\u0026#34;AAbstractClass : I am doing something\u0026#34;); } } public interface IInterface { void canIDoSomething(); } public class UsageClass { public void useAbstractClass(AAbstractClass abstractClassObj) { abstractClassObj.doSomething(); abstractClassObj.iAmDoingSomething(); } public void useInterface(IInterface iInterfaceObject) { iInterfaceObject.canIDoSomething(); } } Now to use the functions in the UsageClass,\n//Java code UsageClass usageClass = new UsageClass(); usageClass.useAbstractClass(new AAbstractClass() { @Override void doSomething() { System.out.println(\u0026#34;UsageClass : I am doing something\u0026#34;); } }); usageClass.useInterface(new IInterface() { @Override public void canIDoSomething() { System.out.println(\u0026#34;UsageClass : can I Do Something\u0026#34;); } }); The equivalent Kotlin code for the same using object expression will be,\n//Kotlin code abstract class AAbstractClass { internal abstract fun doSomething() fun iAmDoingSomething() { println(\u0026#34;AAbstractClass : I am doing something\u0026#34;) } } interface IInterface { fun canIDoSomething() } class UsageClass { fun useAbstractClass(abstractClassObj: AAbstractClass) { abstractClassObj.doSomething() abstractClassObj.iAmDoingSomething() } fun useInterface(iInterfaceObject: IInterface) { iInterfaceObject.canIDoSomething() } fun useSomeClass(someClassObj: AClass) { someClassObj.someFunction() } } To use the UsageClass,\n//Kotlin code val usageClass = UsageClass() usageClass.useAbstractClass(object : AAbstractClass() { override fun doSomething() { println(\u0026#34;UsageClass : I am doing something\u0026#34;) } }) usageClass.useInterface(object : IInterface { override fun canIDoSomething() { println(\u0026#34;UsageClass : can I Do Something\u0026#34;) } }) If a supertype has a constructor, appropriate constructor parameters must be passed to it. Many supertypes may be specified as a comma-separated list after the colon :\n//Kotlin code open class BClass(val x: Int){ open val y = 20 } interface IInterface { fun canIDoSomething() } val bClassObj : BClass = object : BClass(10), IInterface { override val y: Int = 30 override fun canIDoSomething() { println(\u0026#34;bClassObj : can I do something\u0026#34;) } } We can even create just an object with no nontrivial supertypes. This is called an anonymous object.\n//Kotlin code val justAnObject = object { var x = 10 var y = 20 fun sum(): Int = x + y } But the anonymous objects can only be used as types only in local and private declarations. If you use an anonymous object as a return type of a public function or the type of a public property, the actual type of that function or property will be the declared supertype of the anonymous object, or Any if you didn’t declare any supertype. In that case, the members added in the anonymous object will not be accessible.\n//Kotlin code class CClass { // Private function, so the return type is // the anonymous object type private fun privateFunction() = object { val x: String = \u0026#34;x\u0026#34; } // Public function, so the return type is Any fun publicFunction() = object { val x: String = \u0026#34;x\u0026#34; } fun main() { val x1 = privateFunction().x // Works fine val x2 = publicFunction().x // ERROR: //Unresolved reference \u0026#39;x\u0026#39; } } One last thing, unlike Java we can access non-final variables also inside an object expression.\n//Java code int value = 0; usageClass.useInterface(new IInterface() { @Override public void canIDoSomething() { value++; // Error // variable \u0026#39;value\u0026#39; is access from withing inner class, needs to be declared final. } }); In Kotlin, this works fine\n//Kotlin code var value = 0 usageClass.useInterface(object : IInterface { override fun canIDoSomething() { value++ // works fine } }) ","tags":["Kotlin"],"title":"Object Expression in Kotlin"},{"categories":["Blog"],"date":"September 4, 2018","permalink":"https://agrawalsuneet.github.io/blogs/equality-in-kotlin/","section":"blogs","summary":"We often need to compare the data of two variables or objects or the references of two objects in Kotlin. This brings in another question, which equality check should we use in which case.\nLet’s figure out what are the types of checks available in Kotlin.\nStructural Equality (‘==’) == operator is used to compare the data of two variables.\nPlease don’t misunderstand this equality operator with the Java == operator as both are different. == operator in Kotlin only compares the data or variables, whereas in Java or other languages == is generally used to compare the references. The negated counterpart of == in Kotlin is != which is used to compare if both the values are not equal to each other.\nReferential equality (‘===’) === operator is used to compare the reference of two variable or object. It will only be true if both the objects or variables pointing to the same object. The negated counterpart of === in Kotlin is !== which is used to compare if both the values are not equal to each other. For values which are represented as primitive types at runtime (for example, Int), the === equality check is equivalent to the == check.\n.equals method equals(other: Any?) method is implemented in Any class and can be overridden in any extending class. .equals method also compares the content of the variables or objects just like == operator but it behaves differently in case of Float and Double comparison.\nThe difference between == and .equals is in case of Float and Double comparison, .equals disagrees with the IEEE 754 Standard for Floating-Point Arithmetic.\nAnd what does disagree with IEEE 754 Standard for Floating-Point Arithmetic mean? It means,\nNaN is considered equal to itself NaN is considered greater than any other element including POSITIVE_INFINITY -0.0 is considered less than 0.0 Confused? Will explain this and everything with examples.\nFirst, let’s compare two primitive type Int variables by all the equal checks.\nval int1 = 10 val int2 = 10 println(int1 == int2) // true println(int1.equals(int2)) // true println(int1 === int2) // true All the above comparisions will print true because primitive datatype only checks the value in case of === also which will be equal in our case.\nNow let’s use the wrapper class instead of Primitive datatype and compare all three equal checks\nval first = Integer(10) val second = Integer(10) println(first == second) //true println(first.equals(second)) //true println(first === second) //false In the above case, the == and .equals prints true because they compare only values whereas === compares the references of the objects which were different so it prints false.\nNow, let’s consider another case where we created our own custom class object and compared with all three checks.\nclass Employee (val name: String) val emp1 = Employee(“Suneet”) val emp2 = Employee(“Suneet”) println(emp1 == emp2) //false println(emp1.equals(emp2)) //false println(emp1 === emp2) //false println(emp1.name == emp2.name) //true println(emp1.name.equals(emp2.name)) //true println(emp1.name === emp2.name) //true The reason for the above comparison is obvious, As Empoyee is not a primitive datatype or wrapper class, all three compared the references, which returns false for all three checks. But in the case of string comparison, if only checks the contents of the string which were equal so it returns true for every case.\nWait, but you said == and .equals only compares the contents of the object which were equal in our case. Exactly. But the content comparison only works if its a data class. If it’s a normal class the compiler consider both the objects as the different objects even if the content is same but if its a data class, the compiler compares the data and return true if the content is same.\nLet’s change the above class to data class.\ndata class Employee (val name: String) val emp1 = Employee(\u0026#34;Suneet\u0026#34;) val emp2 = Employee(\u0026#34;Suneet\u0026#34;) println(emp1 == emp2) //true println(emp1.equals(emp2)) //true println(emp1 === emp2) //false println(emp1.name == emp2.name) //true println(emp1.name.equals(emp2.name)) //true println(emp1.name === emp2.name) //true Last thing, Let’s compare the float values with a negative zero and positive zero.\nval negZero = -0.0f val posZero = 0.0f println(negZero == posZero) //true println(negZero.equals(posZero)) //false println(negZero === posZero) //true As in the case of Float and Double comparison, .equals disagrees with the IEEE 754 Standard for Floating-Point Arithmetic, it returns a false when -0.0 was compared with 0.0 whereas == and === returns true.\nFew things to keep in mind, As there is no constructor as String(“”) in Kotlin, all string comparison will give true if the content will be equal. There’s no point in optimizing code when comparing to null explicitly. a == null will be automatically translated to a === null as null is a reference and at the end, it will a reference check. ","tags":["Kotlin"],"title":"Equality in Kotlin (‘==’, ‘===’ and ‘equals’)"},{"categories":["Blog"],"date":"August 17, 2018","permalink":"https://agrawalsuneet.github.io/blogs/pair-and-triple-in-kotlin/","section":"blogs","summary":"It is a very common use case where we want to return two values from a method, can be either of same data type or can be of different data types.\nWhat usually we do there is either create some local variables if the method is of the same class and set those variables from the method and consume them in the place where needed or we create a class with just two variables and return that class object from the method.\nThis approach works fine but is it worth defining a new class every time when we return two value from a method.\nWhat if we have several methods which return two values but each method returns the values of different data types? Are we going to create a separate class for each method?\nThe answer is NO. Kotlin provides us with a predefined class Pair which can be used for the same. Pair is used to store or return two values of same or different data types. There can or cannot be any relation between both the values. They can be of the same or different data types.\nAnd how do I use it? Initialise it as a simple Pair class object by passing two values to the constructor.\nPair (\u0026#34;Hello\u0026#34;, \u0026#34;How are you\u0026#34;) Pair (\u0026#34;First\u0026#34;, 1) Pair (10, null) Pair (1.5, listOf(null)) var variable1 = \u0026#34;I am a String\u0026#34; var variable2 = 10 Pair (variable1, variable2) And how do I retrieve the values? Either receive them in a single variable and use first and second properties or componentN method to extract the values, or receive in separate variables and use them directly.\nvar pair = Pair(\u0026#34;Hello\u0026#34;, \u0026#34;How are you\u0026#34;) println(pair.first) println(pair.second) println(pair.component1()) println(pair.component2()) //or var (firstName, lastName) = Pair(\u0026#34;Suneet\u0026#34;, \u0026#34;Agrawal\u0026#34;) println(firstName) println(lastName) We can even use a normal method like toString() on this object.\nval pair = Pair(\u0026#34;I am a String\u0026#34;, listOf(1,2,3)) print(pair.toString()) Or we can even call a copy method on a Pair object and change its values but while copying, the data type of the variables should be the same as the one we are trying to change the value of.\nval pair = Pair(\u0026#34;I am a String\u0026#34;, listOf(1,2,3)) print(pair) val anotherPair = pair.copy(first = \u0026#34;I am new String\u0026#34;) print(anotherPair) We can even convert a Pair object to a list using toList() method and get the values using positions or perform other operations.\nval pair = Pair(\u0026#34;I am a String\u0026#34;, 10) val list = pair.toList() println(list[0]) println(list.get(1)) Now What if I want to return three values from a method? Simple, Use Triple class. It does the same functionality with three different properties.\nIt has the third property as third. We can retrieve the third value as either using third or by component3()\nval triple = Triple(\u0026#34;I am a String\u0026#34;, listOf(1,2,3) , 10) println(triple.third) println(triple.component3()) It even supports copy and toList() method which has the same functionality as Pair but with three properties.\nLast Question. What if I want to return four or more values? Now you are getting greedy. Create your data class and return the object of that class.\n","tags":["Kotlin"],"title":"Pair and Triple in Kotlin"},{"categories":["Blog"],"date":"August 10, 2018","permalink":"https://agrawalsuneet.github.io/blogs/native-android-image-sharing-in-unity/","section":"blogs","summary":"In continuation to my previous blogs Native Android in Unity and Native Android text sharing in Unity, will consider another example of native Android screenshot sharing functionality in the unity app.\nIf you have not read the previous blogs, I would strongly recommend to read them first. You can read them on the links below.\nNative Android in Unity Native Android text sharing in Unity As the number says, an image gains more attention than a normal text while sharing. It’s better to challenge a player with your own high score screenshot in games instead of sharing just a plain text.\nAs in the previous post, we saw Android uses an Intent class object to perform any sharing operation and we can use the same Intent class in unity using AndroidJavaClass and AndroidJavaObject.\nWe can share any image (existing or captured screenshot) in native Android using the same Intent class. As we saw in the previous example of native text sharing, we can set the type of sharing to an Intent object. We will set the type of sharing to “image/png” in our case.\nLet’s have a look at its native android code first.\n//Java String screenShotPath = \u0026#34;fireblock_highscore.png\u0026#34;; Uri uriToImage = Uri.fromFile(new File(\u0026#34;file://\u0026#34; + screenShotPath)); String shareSubject = \u0026#34;I challenge you to beat my high score in Fire Block\u0026#34;; String shareMessage = \u0026#34;I challenge you to beat my high score in Fire Block. \u0026#34; + \u0026#34;Get the Fire Block app from the link below. \\nCheers\\n\\n\u0026#34; + \u0026#34;http://onelink.to/fireblock\u0026#34;; Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage); shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSubject); shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage); shareIntent.setType(\u0026#34;image/png\u0026#34;); startActivity(Intent.createChooser(shareIntent, \u0026#34;Share your high score\u0026#34;)); And the Kotlin code will be\n//Kotlin val screenShotPath = \u0026#34;fireblock_highscore.png\u0026#34; val uriToImage = Uri.fromFile(File(\u0026#34;file://\u0026#34; + screenShotPath)) val shareSubject = \u0026#34;I challenge you to beat my high score in Fire Block\u0026#34; val shareMessage = \u0026#34;I challenge you to beat my high score in Fire Block. \u0026#34; + \u0026#34;Get the Fire Block app from the link below. \\nCheers\\n\\n\u0026#34; + \u0026#34;http://onelink.to/fireblock\u0026#34; val shareIntent = Intent() shareIntent.action = Intent.ACTION_SEND shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage) shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSubject) shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage) shareIntent.type = \u0026#34;image/png\u0026#34; startActivity(Intent.createChooser(shareIntent, \u0026#34;Share your high score\u0026#34;)) Now let’s have a look at how we can use the same native Android screenshot share functionality in a unity app.\nThe first thing we need is the screenshot. Unity provides a class named ScreenCapture which has a public static method CaptureScreenshot which do the same functionality for us.\nThis method has two variants (method overloading) but will use the one which takes two parameters as below. The java code for the same will be\nCaptureScreenshot(string filename, int superSize) This method takes the first parameter as the file name in string format with which the screenshot will be saved and the second parameter as the factor by which to increase resolution in int format.\nThe code will look like\n//C# code in unity var screenshotName = \u0026#34;fireblock_highscore.png\u0026#34;; // wait for graphics to render yield return new WaitForEndOfFrame (); string screenShotPath = Application.persistentDataPath + \u0026#34;/\u0026#34; + screenshotName; ScreenCapture.CaptureScreenshot (screenshotName, 1); yield return new WaitForSeconds (0.5f); Now that we got the screenshot captured in png format and saved at the path, we can share this image using the same Intent we used while sharing the normal text. The only difference here will be the sharing type and the attaching of the image to the intent.\n//C# code in unity //create intent for action send AndroidJavaClass intentClass = new AndroidJavaClass(\u0026#34;android.content.Intent\u0026#34;); AndroidJavaObject intentObject = new AndroidJavaObject (\u0026#34;android.content.Intent\u0026#34;); //set action to that intent object intentObject.Call\u0026lt;AndroidJavaObject\u0026gt; (\u0026#34;setAction\u0026#34;, intentClass.GetStatic\u0026lt;string\u0026gt;(\u0026#34;ACTION_SEND\u0026#34;)); Now that we got the intent object, we will set the share type as image/png and attach the screenshot to it. In order to attach the screenshot, we need to convert it into Uniform Resource Identifier (URI) object from the file path.\n//C# code in unity var shareSubject = \u0026#34;I challenge you to beat my high score in\u0026#34; + \u0026#34;Fire Block\u0026#34;; var shareMessage = \u0026#34;I challenge you to beat my high score in Fire Block. \u0026#34; + \u0026#34;Get the Fire Block app from the link below. \\nCheers\\n\\n\u0026#34; + \u0026#34;http://onelink.to/fireblock\u0026#34;; //create URI for that intent AndroidJavaClass uriClass = new AndroidJavaClass (\u0026#34;android.net.Uri\u0026#34;); AndroidJavaObject uriObject = uriClass.CallStatic\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;parse\u0026#34;, \u0026#34;file://\u0026#34; + screenShotPath); //set the type intentObject.Call\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;setType\u0026#34;, \u0026#34;image/png\u0026#34;); //put image and string extra intentObject.Call\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;putExtra\u0026#34;, intentClass.GetStatic\u0026lt;string\u0026gt;(\u0026#34;EXTRA_STREAM\u0026#34;), uriObject); intentObject.Call\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;putExtra\u0026#34;, intentClass.GetStatic\u0026lt;string\u0026gt; (\u0026#34;EXTRA_SUBJECT\u0026#34;), shareSubject); intentObject.Call\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;putExtra\u0026#34;, intentClass.GetStatic\u0026lt;string\u0026gt; (\u0026#34;EXTRA_TEXT\u0026#34;), shareMessage); Now that we have the intent object ready with all the extras to be shared, let’s call the Activity class’ createChooser method and pass the intent object along with the text to be displayed over the apps list. This step is the same what we did while sharing the text.\n//C# code in unity //create current activity object AndroidJavaClass unity = new AndroidJavaClass(\u0026#34;com.unity3d.player.UnityPlayer\u0026#34;); AndroidJavaObject currentActivity = unity.GetStatic\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;currentActivity\u0026#34;); //call createChooser method of activity class AndroidJavaObject chooser = intentClass.CallStatic\u0026lt;AndroidJavaObject\u0026gt;(\u0026#34;createChooser\u0026#34;, intentObject, \u0026#34;Share your high score\u0026#34;); currentActivity.Call (\u0026#34;startActivity\u0026#34;, chooser); The entire script for Android native screenshot sharing in unity (C#) would be\nThe above script can be used in any unity app targeting Android platform to share a text or high score natively in Android.\nUpdate: Native Android text sharing to particular app in Unity Native Android image sharing in Unity using FileProvider ","tags":["Unity","CSharp"],"title":"Native Android image sharing in Unity"},{"categories":["Blog"],"date":"July 27, 2018","permalink":"https://agrawalsuneet.github.io/blogs/extensions-as-members-kotlin/","section":"blogs","summary":"In continuation to my last Medium post Extensions in Kotlin where I explained what are Extensions and how do we use it, this medium post will cover the implementation of Extensions as members of some other class.\nAn extension can be defined as members of some other class also.\nThe benefit of defining an extension as a member of the other class is, we can access all the functions and properties of both the classes inside that extension method.\nLet’s take an example\nclass BaseClass { fun baseClassFunctionality() { } } class OtherClass { fun otherClassFunctionality() { } fun BaseClass.additionalFunctionality() { baseClassFunctionality() otherClassFunctionality() } } We have two classes named BaseClass and OtherClass. We have a method called baseClassFunctionality in BaseClass and otherClassFunctionality in OtherClass. Now, we added an extension function of BaseClass in OtherClass naming additionalFunctionality. The benefit of adding an extension function of BaseClass in OtherClass is we can access all the methods of BaseClass and OtherClass in that method.\nWhat if both the classes have some same method with the same signature? It will call the method of the class for which the extension function is defined. But if we want to call the method of the class in which the extension function is defined, we can use the qualified this expression.\nclass BaseClass { fun printString() { println(\u0026#34;I am in BaseClass\u0026#34;) } } class OtherClass { fun otherClassFunctionality() { BaseClass().additionalFunctionality() } fun printString() { println(\u0026#34;I am in OtherClass\u0026#34;) } fun BaseClass.additionalFunctionality() { printString() this@OtherClass.printString() } } // the output of OtherClass().otherClassFunctionality() //will be I am in BaseClass Extension function as members can also be declared as open and can be overridden in the derived class. Which function will be called will be decided at runtime for virtual methods but statically for extension methods.\nLet me explain this with an example.\nLet’s say we have a class named BaseClass and another class named DerivedClass which is extending the BaseClass.\nNow we have another class called OtherClass having two open extension functions of both BaseClass and DerivedClass (one each). Also, we have one more class extending the OtherClass and overriding both the extension methods.\nopen class BaseClass { } class DerivedClass : BaseClass() { } open class OtherClass { open fun BaseClass.someFunctionality() { println(\u0026#34;BaseClass.someFunctionality in OtherClass\u0026#34;) } open fun DerivedClass.someFunctionality() { println(\u0026#34;DerivedClass.someFunctionality in OtherClass\u0026#34;) } fun caller(baseClass: BaseClass) { baseClass.someFunctionality() } } class DerivedOtherClass : OtherClass() { override open fun BaseClass.someFunctionality() { println(\u0026#34;BaseClass.someFunctionality in DerivedOtherClass\u0026#34;) } override fun DerivedClass.someFunctionality() { println(\u0026#34;DerivedClass.someFunctionality in DerivedOtherClass\u0026#34;) } } Now will consider four different cases which will clear the picture of overriding extension methods.\nOtherClass().caller(BaseClass()) DerivedOtherClass().caller(BaseClass()) OtherClass().caller(DerivedClass()) DerivedOtherClass().caller(DerivedClass()) When we call the caller method of OtherClass with OtherClass reference object and pass the BaseClass object as the parameter. OtherClass().caller(BaseClass()) //the output of the above code will be BaseClass.someFunctionality in OtherClass This will call the extension function of BaseClass defined in OtherClass. There was no confusion because both the references were of the superclasses.\nWhen we call the caller method of OtherClass with DerivedOtherClass reference object and pass the BaseClass object as the parameter. DerivedOtherClass().caller(BaseClass()) //the output of the above code will be BaseClass.someFunctionality in DerivedOtherClass This will call the extension function of BaseClass overridden in DerivedOtherClass.\nThe virtual dependency of OtherClass and DerivedOtherClass was resolved at runtime and it called the DerivedOtherClass’s overridden method.\nWhen we call the caller method of OtherClass with OtherClass reference object and pass the DerivedClass object as the parameter. OtherClass().caller(DerivedClass()) //the output of the above code will be BaseClass.someFunctionality in OtherClass This will call the extension function of BaseClass defined in OtherClass.\nEven though we passed the DerivedClass object as the parameter, it called the BaseClass method only because the extensions are resolved statically.\nIn the caller method, we have defined the parameter type as BaseClass so it will always call BaseClass extension methods only.\nWhen we call the caller method of OtherClass with DerivedOtherClass reference object and pass the DerivedClass object as the parameter. DerivedOtherClass().caller(DerivedClass()) //the output of the above code will be BaseClass.someFunctionality in DerivedOtherClass This will call the extension function of BaseClass overridden in DerivedOtherClass.\nThe reason is the same.\nThe virtual dependency of OtherClass and DerivedOtherClass was resolved at runtime and it called the DerivedOtherClass’s overridden method and because the extensions are resolved statically, it called the BaseClass extension method only.\nAlso, extension utilizes the same visibility of other entities as regular functions declared in the same scope would.\nIf the extension is defined at the top level of the class, it can access all the private variables and functions of that class.\nIf the extension function is defined outside the class, it can not access the private variables or functions of that class.\n","tags":["Kotlin"],"title":"Extensions as Members : Kotlin"},{"categories":["Blog"],"date":"July 13, 2018","permalink":"https://agrawalsuneet.github.io/blogs/companion-object-in-kotlin/","section":"blogs","summary":"Unlike Java or C#, Kotlin doesn’t have static members or member functions. Kotlin recommends to simply use package-level functions instead.\nIf you need to write a function that can be called without having a class instance but needs access to the internals of a class, you can write it as a member of a companion object declaration inside that class. By declaring a companion object inside our class, you’ll be able to call its members with the same syntax as calling static methods in Java/C#, using only the class name as a qualifier.\nHow should I declare a companion object inside a class? Add companion keyword in front of object declaration.\nclass EventManager { companion object FirebaseManager { } } val firebaseManager = EventManager.FirebaseManager Optionally, you can even remove the companion object name also. In that case the name Companion will be used.\nclass EventManager { companion object { } } val firebaseManager = EventManager.Companion Let’s take an example of Singleton class where a single instance of the class exists and we get that instance using getInstance static method.\n//Java code public class EventManager { private static EventManager instance; private EventManager() { } public static EventManager getManagerInstance() { if (instance == null) { instance = new EventManager(); } return instance; } public boolean sendEvent(String eventName) { Log.d(\u0026#34;Event Sent\u0026#34;, eventName); return true; } } Now when we try to implement the same class in the Kotlin, the private static instance and the managerInstance property will be moved to companion object. Rest of the code remains the same.\n//Kotlin code class EventManager { private constructor() { } companion object { private lateinit var instance: EventManager val managerInstance: EventManager get() { if (instance == null) { instance = EventManager() } return instance } } fun sendEvent(eventName: String): Boolean { Log.d(\u0026#34;Event Sent\u0026#34;, eventName) return true; } } And how I use the sendEvent method? When you name the companion object as FirebaseManager val firebaseManager = EventManager.FirebaseManager firebaseManager.managerInstance.sendEvent(\u0026#34;some event\u0026#34;) //or EventManager.FirebaseManager.managerInstance.sendEvent(\u0026#34;Some event\u0026#34;) When you didn’t name the companion object val firebaseManager = EventManager.Companion firebaseManager.managerInstance.sendEvent(\u0026#34;some event\u0026#34;) // or EventManager.Companion.managerInstance.sendEvent(\u0026#34;Some event\u0026#34;) Please keep in mind, even though the members of companion object look like static members in other languages, at runtime those are still instance members of real objects, and can, for example, implement interfaces.\nHowever, if you use the@JvmStatic annotation, you can have members of companion objects generated as real static methods and fields on the JVM.\n//Kotlin code interface EventManagementInterface { fun someMethod() } class EventManager { companion object FirebaseManager : EventManagementInterface { override fun someMethod() { } } } A companion object is initialized when the corresponding class is loaded (resolved), matching the semantics of a Java static initializer. Means that the companion object will be initialized even before calling the constructor of that class as similar to Java static initializer.\n","tags":["Kotlin"],"title":"Companion object in Kotlin"},{"categories":["Blog"],"date":"July 13, 2018","permalink":"https://agrawalsuneet.github.io/blogs/computed-property-in-swift/","section":"blogs","summary":"Object creation is a heavy process. When we create a class object, all the public and private properties of that class are initialised inside the constructor. Every variable inside a class initialisation requires a certain amount of time to allocate the memory on the heap and hold its reference on the stack. The more variables, the more time it may take but since the time is in microseconds or even less, it\u0026rsquo;s not observable.\nSometimes we don\u0026rsquo;t need all the objects to be initialised during the class object creation itself.\nThere can be two reasons for that.\nThat object/property/variable is dependent on another object to initialise first and use its reference. The flow is such that we need that object only in a certain condition. In Swift, we have certain features which can help us in delaying that object initialisation as per the requirement.\nOne way of doing that is using computed properties.\nComputed properties are the properties that don\u0026rsquo;t get initialised while object creation or constructor is called. They get computed every time the property is accessed.\nWe can use it for any heavy computation which we want to do on a conditional basis. Unlike Lazy properties, these properties get computed every time the property is accessed.\nThe basic initialisation of a computed property in a `User class object by will look like below\nstruct User { let name : String let age : Int } struct Department { var users : [User] init(users : [User]) { print(\u0026#34;Department constructor is called\u0026#34;) self.users = users } var youngestUser: User? { print(\u0026#34;Department youngestUser is computed\u0026#34;) return self.users.min(by: {$0.age \u0026lt; $1.age}) } } Let\u0026rsquo;s try to understand what exactly computed property is A Computed property is a delegation of property initialisation that will only be called when that property will be used. This will compute the property every time this property is accessed.\nA Computed property is similar to a normal function which will return a value of certain type but it can\u0026rsquo;t accept parameters.\nLets see this with an example.\nstruct User { let name : String let age : Int } struct Department { var users : [User] init(users : [User]) { print(\u0026#34;Department constructor is called\u0026#34;) self.users = users } var youngestUser : User? { print(\u0026#34;Department youngestUser is computed\u0026#34;) return self.users.min(by: {$0.age \u0026lt; $1.age}) } } var engineeringDepartment = Department(users: [ User(name: \u0026#34;Suneet\u0026#34;, age: 29), User(name: \u0026#34;Ballu\u0026#34;, age: 20), User(name: \u0026#34;Agrawal\u0026#34;, age: 50) ]) //This will print: Department constructor is called print(engineeringDepartment.youngestUser ?? \u0026#34;\u0026#34;) //This will print: Department youngestUser is computed //followed by : User(name: \u0026#34;Ballu\u0026#34;, age: 20) As we can see the computed property was not initialised even when we initialised the `Department class object. That only got initialised when we called the computed property.\nThings to keep in mind while working with computed property Can only be a var type caomputed property can only be var but it can't a let (immutable) property.\nclass Department { //... let youngestUser : User? { \u0026lt;e\u0026gt;//\u0026#39;let\u0026#39; declarations cannot be computed properties\u0026lt;/e\u0026gt; return self.users.min(by: {$0.age \u0026lt; $1.age}) } } Can be of primitive or non-primitive type A computed property can be of primitive or non-primitive type.\nclass Department { //... var youngestUserAge : Int? { return self.users.min(by: {$0.age \u0026lt; $1.age})?.age } var youngestUser : User? { return self.users.min(by: {$0.age \u0026lt; $1.age}) } } Can be used inside or outside a class or struct. A computed property can be used outside a class or struct also.\nvar pi : Float { return 22/7 } print(pi) The struct or class object accessing computed property should also be var The object which is trying to access the computed property should also be mutable means `var.\nclass Department { //... var youngestUser : User? { print(\u0026#34;Department youngestUser is computed\u0026#34;) return self.users.min(by: {$0.age \u0026lt; $1.age}) } } let engineeringDepartment = Department(users: [ User(name: \u0026#34;Suneet\u0026#34;, age: 29), User(name: \u0026#34;Ballu\u0026#34;, age: 20), User(name: \u0026#34;Agrawal\u0026#34;, age: 50) ]) print(engineeringDepartment.youngestUser ?? \u0026#34;\u0026#34;) //error: Cannot assign to property: \u0026#39;engineeringDepartment\u0026#39; is a \u0026#39;let\u0026#39; constant Please note that it\u0026rsquo;s not compulsory to create all the objects of that class or struct should be var but in order to access the computed property, the variable should be var (mutable) type.\nCan also be defined in extensions A computed property can also be defined in an extension of the class.\nclass Department { var users : [User] init(users : [User]) { print(\u0026#34;Department constructor is called\u0026#34;) self.users = users } } extension Department { var youngestUser : User? { return self.users.min(by: {$0.age \u0026lt; $1.age}) } } Can also be overridden A computed property can also be overridden in a class by adding `override to the property in the extending class.\nclass Department { var users : [User] init(users : [User]) { print(\u0026#34;Department constructor is called\u0026#34;) self.users = users } var youngestUser : User? { print(\u0026#34;Department youngestUser is computed\u0026#34;) return self.users.min(by: {$0.age \u0026lt; $1.age}) } } class SubDeppartment : Department { override var youngestUser : User? { print(\u0026#34;SubDeppartment youngestUser is computed\u0026#34;) return self.users.max(by: {$0.age \u0026lt; $1.age}) } } The value will be computed every time when the property will be accessed The computation of the computed property will only every time when the property will be accessed.\nvar engineeringDepartment = Department(users: [ User(name: \u0026#34;Suneet\u0026#34;, age: 29), User(name: \u0026#34;Ballu\u0026#34;, age: 20), User(name: \u0026#34;Agrawal\u0026#34;, age: 50) ]) print(engineeringDepartment.youngestUser ?? \u0026#34;\u0026#34;) //This will print: User(name: \u0026#34;Ballu\u0026#34;, age: 20) engineeringDepartment.users.append(User(name: \u0026#34;John\u0026#34;, age: 18)) //or engineeringDepartment.users = [User(name: \u0026#34;John\u0026#34;, age: 18)] print(engineeringDepartment.youngestUser ?? \u0026#34;\u0026#34;) //This will print: User(name: \u0026#34;John\u0026#34;, age: 18) Can add get wrapper also to the property getter but that is optional We can add a get wrapper also to the property\u0026rsquo;s getter but that is optional. It\u0026rsquo;s not recommended.\nvar youngestUser : User? { get { return self.users.min(by: {$0.age \u0026lt; $1.age}) } } Is get-only Unlike the stored properties, We can\u0026rsquo;t assign a value to a computed property as they are get-only properties.\nengineeringDepartment.youngestUser = User(name: \u0026#34;John\u0026#34;, age: 18) \u0026lt;e\u0026gt;//cannot assign to property: \u0026#39;youngestUser\u0026#39; is a get-only property\u0026lt;/e\u0026gt; Few things to remember about computed property A computed property is used to delay the initialisation of property and it will be computed every time when that property will be called. This is similar to a function only but it doesn\u0026rsquo;t take any parameter.\nAlso, it can be used inside or ouside a class or struct or even in extensions and the calling object should also be `var.\n","tags":["Swift"],"title":"Computed Property in Swift"},{"categories":["Blog"],"date":"June 29, 2018","permalink":"https://agrawalsuneet.github.io/blogs/native-android-text-sharing-in-unity/","section":"blogs","summary":"In continuation to my previous blogs Native Android in Unity, will consider another example of native Android text sharing functionality in the unity app. This is a very common requirement in any unity app targeting Android platform to share the high score or challenge other players with a text message or a screenshot of the high score. The sharing can be done via any of the app available on the user’s device which supports sharing.\nAndroid provides a native share functionality to do the same where we provide the text and/or the image to share to the Android system and Android provides a list of available apps on the device to share, where the user can pick one app to perform the share action.\nNow let’s see first how sharing works in native Android.\nAndroid uses Intent to do the same.\nFor those who are new to native Android, An intent is an abstract description of an operation to be performed.\nIn an intent, we can set the action to be performed (sharing in our case), set the type of extras we will share ( text, image or any other format), pass all the extras to be shared (text and/or image) and finally call the Android system to provide the list of the available apps in the device which accepts this type of sharing.\nThe java code for the same will be\n//Java String shareSubject = \u0026#34;I challenge you to beat my high score in Fire Block\u0026#34;; String shareMessage = \u0026#34;I challenge you to beat my high score in Fire Block. \u0026#34; + \u0026#34;Get the Fire Block app from the link below. \\nCheers\\n\\n\u0026#34; + \u0026#34;http://onelink.to/fireblock\u0026#34;; Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSubject); sendIntent.putExtra(Intent.EXTRA_TEXT, shareMessage); sendIntent.setType(\u0026#34;text/plain\u0026#34;); startActivity(Intent.createChooser(sendIntent, \u0026#34;Share Via\u0026#34;)); And the Kotlin code will be\n//Kotlon val shareSubject = \u0026#34;I challenge you to beat my high score in Fire Block\u0026#34; val shareMessage = \u0026#34;I challenge you to beat my high score in Fire Block. \u0026#34; + \u0026#34;Get the Fire Block app from the link below. \\nCheers\\n\\n\u0026#34; + \u0026#34;http://onelink.to/fireblock\u0026#34; val sendIntent = Intent() sendIntent.action = Intent.ACTION_SEND sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSubject) sendIntent.putExtra(Intent.EXTRA_TEXT, shareMessage) sendIntent.type = \u0026#34;text/plain\u0026#34; startActivity(Intent.createChooser(sendIntent, \u0026#34;Share Via\u0026#34;)) Let’s see how we can use the same native Android share functionality in a unity app. As in the previous post about Native Android in Unity we learnt that we can use all the native android classes in unity using AndroidJavaClass and AndroidJavaObject\nLet’s use these classes and go step by step. First will create an AndroidJavaClass object of Intent class and will create and AndroidJavaObject of that class.\n//C# code in unity //create intent for action send AndroidJavaClass intentClass = new AndroidJavaClass(\u0026#34;android.content.Intent\u0026#34;); AndroidJavaObject intentObject = new AndroidJavaObject(\u0026#34;android.content.Intent\u0026#34;); //set action to that intent object intentObject.Call\u0026amp;lt;AndroidJavaObject\u0026amp;gt;(\u0026#34;setAction\u0026#34;, intentClass.GetStatic\u0026amp;lt;string\u0026amp;gt; (\u0026#34;ACTION_SEND\u0026#34;)); Next will set the share type as text and set extra subject and text to be shared.\n//C# code in unity var shareSubject = \u0026#34;I challenge you to beat my high score in\u0026#34; + \u0026#34;Fire Block\u0026#34;; var shareMessage = \u0026#34;I challenge you to beat my high score in Fire Block. \u0026#34; + \u0026#34;Get the Fire Block app from the link below. \\nCheers\\n\\n\u0026#34; + \u0026#34;http://onelink.to/fireblock\u0026#34;; //set the type as text and put extra subject and text to share intentObject.Call\u0026amp;lt;AndroidJavaObject\u0026amp;gt;(\u0026#34;setType\u0026#34;, \u0026#34;text/plain\u0026#34;); intentObject.Call\u0026amp;lt;AndroidJavaObject\u0026amp;gt;(\u0026#34;putExtra\u0026#34;, intentClass.GetStatic\u0026amp;lt;string\u0026amp;gt; (\u0026#34;EXTRA_SUBJECT\u0026#34;), shareSubject); intentObject.Call\u0026amp;lt;AndroidJavaObject\u0026amp;gt;(\u0026#34;putExtra\u0026#34;, intentClass.GetStatic\u0026amp;lt;string\u0026amp;gt; (\u0026#34;EXTRA_TEXT\u0026#34;), shareMessage); Now that we have the intent object ready with all the extras to be shared, let’s call the Activity class’ createChooser method and pass the intent object along with the text to be displayed over the apps list.\n//C# code in unity //create current activity object AndroidJavaClass unity = new AndroidJavaClass(\u0026#34;com.unity3d.player.UnityPlayer\u0026#34;); AndroidJavaObject currentActivity = unity.GetStatic\u0026amp;lt;AndroidJavaObject\u0026amp;gt; (\u0026#34;currentActivity\u0026#34;); //call createChooser method of activity class AndroidJavaObject chooser = intentClass.CallStatic\u0026amp;lt;AndroidJavaObject\u0026amp;gt; (\u0026#34;createChooser\u0026#34;, intentObject, \u0026#34;Share your high score\u0026#34;); currentActivity.Call (\u0026#34;startActivity\u0026#34;, chooser); The entire script for Android native text sharing in unity (C#) would be\nThe above script can be used in any unity app targeting Android platform to share a text or high score natively in Android.\nUpdate: Native Android image sharing in Unity Android image sharing in Unity using FileProvider ","tags":["Unity","CSharp"],"title":"Native Android text sharing in Unity"},{"categories":["Blog"],"date":"June 22, 2018","permalink":"https://agrawalsuneet.github.io/blogs/native-android-in-unity/","section":"blogs","summary":"While developing unity games in C# targeting android platform, we always want to use few native android features in our game. These features can be showing notifications on certain actions in the game or can be sharing the high score with other players and inviting them to try our game using android native share. Android gives us all the possibilities to achieve these native android functionalities in unity app using C#.\nLet’s take a very basic example of native android functionality ie showing a Toast using unity app.\nFor all those who are not familiar with what a toast is, toast is a simple message popup that appears at the bottom side (by default) of the screen with a custom message and for a long or short duration. A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.\nTo show this toast in native android we need a simple call to the Toast class static method makeText which return us a Toast class object and then call show method on that object.\n//Java Code Context context = getApplicationContext(); CharSequence text = \u0026#34;This is a toast\u0026#34;; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); //Kotlin Code val text = \u0026#34;This is a toast\u0026#34; val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(applicationContext, text, duration) toast.show() makeText accepts three arguments,\nContext : the reference of current activity or application.\nText to show (CharSequence): text needs to be displayed\nDuration (int): duration for which the toast needs to be displayed\nThe duration value can choose between Toast.LENGTH_LONG or Toast.LENGTH_SHORT.\nNow in order to show the same code in unity app, we need use the same Toast class of android but how?\nusing AndroidJavaClass and AndroidJavaObject.\nAndroidJavaClass is the Unity representation of a generic instance of java.lang.Class whereas AndroidJavaObject is the Unity representation of a generic instance of java.lang.Object.\nFirst, lets put a Platform #define directives because this particular piece of code will only be supported on the Android platform\n//C# code #if UNITY_ANDROID //our entire code //.. #endif Next, create a new AndroidJavaClass object of Toast class.\n//C# code AndroidJavaClass toastClass = new AndroidJavaClass(\u0026#34;android.widget.Toast\u0026#34;); The constructor of AndroidJavaClass takes a string object as the argument. The string should be the fully qualified name (\u0026lt;packagename\u0026gt;.\u0026lt;classname\u0026gt;) of the class whose reference need to be created. In our case, the fully qualified name of Toast class will be android.widget.Toast which can be obtained from the official documents of Toast class here.\nNow, as we know that makeText method of Toast class accepts three arguments, but the AndroidJavaObject.Call or AndroidJavaObject.CallStatic method accepts all the arguments as an object array so let’s create an object array with all the required arguments in it.\n//C# code //create an object array of 3 size object[] toastParams = new object[3]; //create a class reference of unity player activity AndroidJavaClass unityActivity = new AndroidJavaClass (\u0026#34;com.unity3d.player.UnityPlayer\u0026#34;); //set the first object in the array //as current activity reference toastParams[0] = unityActivity.GetStatic\u0026amp;lt;AndroidJavaObject\u0026amp;gt; (\u0026#34;currentActivity\u0026#34;); //set the second object in the array //as the CharSequence to be displayed toastParams[1] = \u0026#34;This is a Toast\u0026#34;; //set the third object in the array //as the duration of the toast from toastParams[2] = toastClass.GetStatic\u0026amp;lt;int\u0026amp;gt; (\u0026#34;LENGTH_LONG\u0026#34;); The thing to notice here is the AndroidJavaObject.GetStatic method. This method is used to get the value of a static field in an object type.\nNow that we have the object array ready, let’s call the makeText method of Toast class with passing the object array as an argument.\n//C# code AndroidJavaObject toastObject = toastClass.CallStatic\u0026amp;lt;AndroidJavaObject\u0026amp;gt; (\u0026#34;makeText\u0026#34;, toastParams); AndroidJavaObject.CallStatic method is used to call a static Java method on a class. This method returns us an AndroidJavaObject class object which is the Toast class object in our case. We can call the show method on this object now.\n//C# code toastObject.Call (\u0026#34;show\u0026#34;); AndroidJavaObject.Call method is used to call a Java method on an object (non-static).\nThe entire code put together will be\nThis will show the required native toast. This toast can be shown on any button click, on start/update or any other method of any game object, on some action performed or network call response, anywhere.\nUpdate: Native Android text sharing in Unity Native Android image sharing in Unity ","tags":["Unity","CSharp"],"title":"Native Android in Unity"},{"categories":["Blog"],"date":"June 15, 2018","permalink":"https://agrawalsuneet.github.io/blogs/the-nothing-type-kotlin/","section":"blogs","summary":"What if I say there is a class called Nothing in Koltin.\nAnd What does it do? Nothing. The time I read about the class Nothing for the first time, it sounds interesting to me. This class has no instance and it is used to represent a value which never exists. This class is also used to represent a return type from a method that will never return.\nConfused? Let me explain. If we use null to initialize a value of an inferred type and there is no other information that can be used to determine a more specific type, the compiler considers it as Nothing? type.\nval variable = null //compiler will read this as // val variable : Nothing? = null val list = listOf(null) //compiler will read this as //val list : List\u0026lt;Nothing?\u0026gt; = listOf(null) The type of variable will be Nothing?. Or even if we initialize a list of nulls, the compiler will consider it as a list of Nothing? type.\nNothing has no type and can also be used to mark code locations that can never be reached. Let’s say we have a method which throws an exception. The return type of that method would be Nothing type.\nfun throwException(message: String): Nothing { throw IllegalArgumentException(message) } As looking at the above method, we are pretty sure that the method will never return and will throw an exception before that. The return type can be denoted by Nothing class. We could have used void type also in place of Nothing in the same method but in that case, the compiler won’t be sure that the method will return or not. But if we replace the return type by Nothing, the compiler will be sure that this will never return.\nfun throwException(message: String) { throw IllegalArgumentException(message) } As we know that throw is an expression in Kotlin and can be used as a part of Elvis operator also.\nval personName = person.name ?: throw IllegalArgumentException(\u0026#34;Name required\u0026#34;) The above code can be replace with\nfun throwException(message: String): Nothing { throw IllegalArgumentException(message) } val personName = person.name ?: throwException(\u0026#34;Name required\u0026#34;) //we are sure that personName is not null println(personName) And the compiler will know that the execution will not continue if the value of personName is null\nThat’s it. So What did we learn today?\nNothing ","tags":["Kotlin"],"title":"The Nothing Type : Kotlin"},{"categories":["Blog"],"date":"June 8, 2018","permalink":"https://agrawalsuneet.github.io/blogs/label-reference-in-kotlin/","section":"blogs","summary":"Any expression in Kotlin may be marked with a label. This can be used to as an identifier. A label can be defined in Kotlin using label name followed by @ sign in front of any expression.\nLet me give you an example\nloopi@ for( i in 1..5){ print(i) } But what is the use? Where I am going to use this label and why would I use it?\nThese labels are really helpful when dealing with nested loops or nested functions.\nWill explain the use cases in detail of label references but before that, we need to understand what are jump and return expressions.\nbreak : Terminates the nearest enclosing loop. continue : Proceeds to the next step of the nearest enclosing loop. return : Return from the nearest enclosing function or anonymous function. Now let’s take an example of nested loop first to understand the use of label reference.\nfor( i in 1..3){ for (j in 5..7){ print ((i * 100) + j) print(\u0026#34; \u0026#34;) } println( i.toString() + \u0026#34; loop ends\u0026#34;) } println(\u0026#34;We are done\u0026#34;) The output of the above code is\n105 106 107 1 loop ends 205 206 207 2 loop ends 305 306 307 3 loop ends We are done Now in the above example, what if I want to break the i loop (means the entire execution of loops) when i equals to 2 and j equals to 6 but still want to execute below code of lines.\nMeans I want the output as\n105 106 107 1 loop ends 205 We are done I’ll use a break statement with if condition (i == 2 \u0026amp;\u0026amp; j == 6) inside the j loop and another if condition (i == 2) after execution of j loop.\nfor( i in 1..3){ for (j in 5..7){ if(i == 2 \u0026amp;\u0026amp; j == 6) break print ((i * 100) + j) print(\u0026#34; \u0026#34;) } if(i == 2) break println( i.toString() + \u0026#34; loop ends\u0026#34;) } println(\u0026#34;We are done\u0026#34;) We need to add two condition checks and break statements because the break statement only works for the nearest enclosing loop.\nWhat if I say there is a better way to do the same in Kotlin.\nLabel the i loop and break the same loop using label reference by checking the condition inside the j loop.\nloopi@ for( i in 1..3){ for (j in 5..7){ if(i == 2 \u0026amp;\u0026amp; j == 6) break@loopi print ((i * 100) + j) print(\u0026#34; \u0026#34;) } println( i.toString() + \u0026#34; loop ends\u0026#34;) } println(\u0026#34;We are done\u0026#34;) In the above code, we labelled the outer loop as loopi and while checking the condition we break the loop using the same label. And this will break the entire execution of the loops when the condition will be true.\nThe same can be used with continue expression also. The continue expression also works for the nearest enclosing loop but if we want to continue the outer loop, we can use the label reference.\nloopi@ for( i in 1..3){ for (j in 5..7){ if(i == 2 \u0026amp;\u0026amp; j == 6) continue@loopi print ((i * 100) + j) print(\u0026#34; \u0026#34;) } println( i.toString() + \u0026#34; loop ends\u0026#34;) } println(\u0026#34;We are done\u0026#34;) And the output will be\n105 106 107 1 loop ends 205 305 306 307 3 loop ends We are done Now that we understand that labels can be used to break or continue the non-nearest enclosing loops, lets understand the use of label reference in return expression.\nWith function literals, local functions and object expression, functions can be nested in Kotlin. Qualified returns allow us to return from an outer function.\nLets take an example of labmda expression.\nfun somefunction() { listOf(1, 2, 3, 4, 5).forEach { if (it == 3) return print(it) println() } println(\u0026#34;I will never be printed :( \u0026#34;) } In the above code, the function will return from the outer most function when the condition will be true and the output will be\n1 2 If we need to return from a lambda expression, we have to label it and qualify the return.\nfun somefunction() { listOf(1, 2, 3, 4, 5).forEach lambda@{ if (it == 3) return@lambda print(it) print(\u0026#34; \u0026#34;) } println(\u0026#34;I\u0026#39;ll be printed too :) \u0026#34;) } And the output will be\n1 2 4 5 I\u0026#39;ll be printed too :) The reason why 4 and 5 were printed is that the forEach loop was called for each and every value separately. The condition for it == 3 passes and return for that condition only but not for 4 and 5.\nWe can even use the implicit labels that are the same name as the function to which the lambda is passed and we don’t have to define the label explicitly.\nfun somefunction() { listOf(1, 2, 3, 4, 5).forEach { if (it == 3) return@forEach print(it) print(\u0026#34; \u0026#34;) } println(\u0026#34;I\u0026#39;ll be printed too :) \u0026#34;) } In the above example, we can even replace the lambda expression with an anonymous function. A return statement in an anonymous function will return from the anonymous function only and rest of the code will execute normally.\nfun somefunction() { listOf(1, 2, 3, 4, 5).forEach(fun(value: Int) { if (value == 3) return print(value) print(\u0026#34; \u0026#34;) }) print(\u0026#34;I\u0026#39;ll be printed too :) \u0026#34;) } The above code works as similar to the continue statement in for loop and will still print 4 and 5. If we want to break the loop or function execution based on some condition, we can use a nested labmda expression along with label referencing.\nfun somefunction() { run loop@{ listOf(1, 2, 3, 4, 5).forEach { if (it == 3) return@loop print(it) print(\u0026#34; \u0026#34;) } } print(\u0026#34;Now I\u0026#39;ll be printed too :) \u0026#34;) } In the above code, the inner lambda expression will return from outer lambda expression that is labelled as loop based on the condition and will execute after the outer lambda expression.\nThe output for the above code will be\n1 2 I\u0026#39;ll be printed too :) ","tags":["Kotlin"],"title":"Label Reference in Kotlin"},{"categories":["Blog"],"date":"May 21, 2018","permalink":"https://agrawalsuneet.github.io/blogs/tuple-in-swift/","section":"blogs","summary":"It is a very common use case where we want to return two values from a method, can be either of same data type or can be of different data types.\nWhat usually we do there is either create some local variables if the method is of the same class and set those variables from the method and consume them in the place where needed or we create a struct with just two variables and return that struct object from the method.\nThis approach works fine but is it worth defining a new struct every time when we return two value from a method.\nWhat if we have several methods which return two values but each method returns the values of different data types?\nAre we going to create a separate struct for each method?\nThe answer is NO. Swift provides us with a type called Tuple which is used to group multiple values in a single compound value. Tuple is used to store or return two values of same or different data types. There can or cannot be any relation between both the values.\nAnd how do I use it? It can be initialised in two ways.\nUnnamed variables Named variables Unnamed variables Tuple Unnamed variables Tuple is where we don\u0026rsquo;t define the names to the Tuple variables and while using them, we use their position to access it.\nvar tuple = (\u0026#34;Suneet\u0026#34;, \u0026#34;Agrawal\u0026#34;) print(tuple.0) print(tuple.1) Named variables Tuple Named variables Tuple is where we define the names of the Tuple variables and while using them, we can use the same names with which we defined them with.\nvar tuple = (firstName : \u0026#34;Suneet\u0026#34;, lastName : \u0026#34;Agrawal\u0026#34;) print(tuple.firstName) print(tuple.lastName) To define the type of Tuple we can simply use brackets () and define the type inside it.\nvar tuple : (String, Int) func getEmployeeDetails() -\u0026gt; (String, Int) { return (name : \u0026#34;Suneet Agrawal\u0026#34;, employeeId : 100) } What if I want to return three values from a method? There is no direct way or type defined in Swift but as a work around we can put a Tuple inside another Tuple but keep in mind it might overcomplicate your code so use it wisely.\nvar tuple = (name : (firstName: \u0026#34;Suneet\u0026#34;, lastName : \u0026#34;Agrawal\u0026#34;), employeeId : 100) print(tuple.name.firstName) print(tuple.name.lastName) print(tuple.employeeId) Last Question. What if I want to return four or more values? You can put as many Tuple inside each other as you want but now you are getting greedy. I\u0026rsquo;ll suggest to create your own struct and return the object of it.\n","tags":["Swift"],"title":"Tuple in Swift"},{"categories":["Blog"],"date":"March 3, 2018","permalink":"https://agrawalsuneet.github.io/blogs/property-getter-and-setter-kotlin/","section":"blogs","summary":"I started developing Android apps in Java where encapsulation of object-oriented programming was achieved through declaring variables as private fields with their getter and setter as public methods. The moment I converted my Java code to Kotlin, it replaced each variable along with its getter and setter with just a single line of code. Although I was amazed at how can a single line of code replace the complete variable with the same functionality, but later on understanding it, I started liking writing the code in Kotlin. Let’s understand how it works in Kotlin.\nVariable having a class level scope (member variables) which are declared inside the class but outside the methods or functions is called as Property in Kotlin. They are declared with var keyword for a mutable one and with val keyword for a read-only/nonmutable one.\nThe full syntax for declaring a property is\nvar \u0026lt;propertyName\u0026gt;: \u0026lt;PropertyType\u0026gt; = \u0026lt;property_initializer\u0026gt; [\u0026lt;getter\u0026gt;] [\u0026lt;setter\u0026gt;] The initializer, getter and setter are optional.\nval name : String = \u0026#34;John\u0026#34; var age : Int = 0 which is exactly the replacement of\npublic final String name = \u0026#34;John\u0026#34;; public int age = 0; Things to notice No need to add public modifier as by default, all properties and functions are public in Kotlin. Add private or protected if required. A property must be initialized or need to be declared as abstract in Kotlin . Instead, we can even use lateinit which is better explained here. All properties are final by default. If you want to override some property or its getter setter, define the property as open(explained later in the same post). But we just broke the rule of encapsulation by defining a variable as public. What if I want to declare the variable as private having a getter and a setter as public methods.\nprivate String name; public String getName() { return name; } public void setName(String name) { this.name = name; } Here we go.\nvar name: String = “John” Where are my getter and setter? Trust me, they are there. No need to define them explicitly.\nOk, I Trust you. What if I want to override the getter and setter.\nprivate int size = 0; private boolean isEmpty; public boolean isEmpty() { return size == 0; } absolutely simple.\nprivate val size : Int = 0 var isEmpty: Boolean = false private set get () = size == 0 Please note that the setter is set private here as it can’t be set from outside the class.\nThis was an easy one. Let me try something complicated.\nwhat about this.\nprivate String firstName; private String lastName; //private String name; public String getName() { return firstName + \u0026#34; \u0026#34; + lastName; } public void setName(String name) { String nameArray[] = name.split(\u0026#34; \u0026#34;); firstName = nameArray[0]; lastName = nameArray[1]; } I have three private variables firstName, lastName and name but only getter setter of name variable which does break the name into two parts and store them in firstName and lastName respectively in case of the setter.\nAlso, in case of the getter, it returns the firstName and lastName with a space between them.\nWhat will be the equivalent Kotlin code for this?\nWell, it’s not that difficult.\nprivate var firstName: String? = null private var lastName: String? = null var name: String get() = firstName + \u0026#34; \u0026#34; + lastName set(value) { val nameArray = value.split(\u0026#34; \u0026#34;.toRegex()) firstName = nameArray[0] lastName = nameArray[1] } Ok. Few questions\n1. How can I make setter private? Add private keyword before set.\npublic var name: String = \u0026#34;John\u0026#34; private set 2. How can I override the getter or setter in an extending class? Define the variable as open in the base class and use override keyword in the extending class.\n//Base class open var age: Int = 0 get() = 10 //Extending class override var age: Int = 0 get()= 20 ","tags":["Kotlin"],"title":"Property, Getter and Setter : Kotlin"},{"categories":["Blog"],"date":"January 12, 2018","permalink":"https://agrawalsuneet.github.io/blogs/kotlin-for-loop/","section":"blogs","summary":"While converting all my java code to kotlin, one of the strange syntax change I observed was the for loop in both the languages. Later I realized in Kotlin, there are few concepts which are completely different from java or any other another language for loops.\nWait! They are not this tough. In fact, they are very easy, interesting and helpful.\nLet’s check one by one.\n1. Simple for loop in java that iterates from some number to some number incrementing one on each loop pass. \u0026lt;l\u0026gt;Java code\u0026lt;/l\u0026gt; for (int i = 0; i \u0026lt;= 10; i++){ System.out.print(i); } its equivalent Kotlin code\n\u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; for (i in 0..10) { print(i) } Things to notice No need to declare the data type of variable If iterating over a range, we can use in variable The lower and upper (including) limit can be defined on both the sides of .. operator. 2. Now let’s say if I don’t don’t want to include the upper limit in the loop and break the loop if it hits the upper limit. \u0026lt;l\u0026gt;Java code\u0026lt;/l\u0026gt; for (int j = 0; j \u0026lt; 10; j++) { System.out.print(j); //this will print only up to 9 } There are two ways to do the same in kotlin, the first one is decrement the upper limit it while coding and use .. operator or another way is use until operator.\n\u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; for (j in 0..9) { print(j) } for (j in 0 until 10) { print(j) } Both do the same thing.\n3. I want to increment it by 2 or some other number. \u0026lt;l\u0026gt;Java code\u0026lt;/l\u0026gt; for (int i = 0; i \u0026lt;= 10; i += 2) { System.out.print(i); } We can use step operator here\n\u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; for (i in 0..10 step 2) { print(i) } 4. Wait, what if I want to run the loop in reverse order. Can I use 10..1 ? \u0026lt;l\u0026gt;Java code\u0026lt;/l\u0026gt; for (int i = 10; i \u0026gt; 0; i--) { System.out.print(i); } No, you can not use 10..1 as .. operator never works on the reverse ranges. It won’t give you a compile time or run time error but simply skips the loops by checking the conditions which will be false every time. You have to use downTo operator.\n\u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; for (i in 10 downTo 1) { print(i) } You can also change the step size with step operator.\n\u0026lt;l\u0026gt;Java code\u0026lt;/l\u0026gt; for (int i = 10; i \u0026gt; 0; i -= 3) { System.out.print(i); } \u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; for (i in 10 downTo 1 step 3) { print(i) } But please note that until operator doesn’t work here. until operator can only be used for forward increments.\n5. What if I have a complex calculation instead of addition or subtraction in each step. Let’s say multiplication or division. \u0026lt;l\u0026gt;Java code\u0026lt;/l\u0026gt; for (int k = 2; k \u0026lt;= 256; k *= 2) { System.out.print(k); } Move to while loop, no other way\n\u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; var k = 2 while (k \u0026lt;= 256) { print(k) k *= 2 } 6. I want to iterate over an array now. \u0026lt;l\u0026gt;Java code\u0026lt;/l\u0026gt; int[] arr = new int[5]; for (int i = 0; i \u0026lt; arr.length; i++) { System.out.print(arr[i]); } Simple, us the indices in kotlin\n\u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; val arr = IntArray(5) for (i in arr.indices) { print(arr[i]) } 7. I heard about some for foreach also. Can I use the same in kotlin? \u0026lt;l\u0026gt;Java code\u0026lt;/l\u0026gt; int[] arr = new int[5]; for (int item: arr) { System.out.print(item); } Yes, you can. for loop iterates through anything that provides an iterator. A for loop over an array is compiled to an index-based loop that does not create an iterator object.\n\u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; for(item in arr){ print(item) } 8. And what about List? \u0026lt;l\u0026gt;Java code\u0026lt;/l\u0026gt; List\u0026lt;Integer\u0026gt; arrayList = new ArrayList\u0026lt;\u0026gt;(); for (int i = 0; i \u0026lt; arrayList.size(); i++) { System.out.print(arrayList.get(i)); } List\u0026lt;Integer\u0026gt; vector = new Vector\u0026lt;\u0026gt;(); for (int i = 0; i \u0026lt; vector.size(); i++) { System.out.print(vector.get(i)); } Simple. Use indices based iteration.\n\u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; val arrayList = ArrayList\u0026lt;Int\u0026gt;() for (i in arrayList.indices) { print(arrayList[i]) } val vector = Vector\u0026lt;Int\u0026gt;() for (i in vector.indices) { print(vector[i]) } No, I am a fan of foreach loop.\n\u0026lt;l\u0026gt;Java code\u0026lt;/l\u0026gt; for (int item : arrayList) { System.out.print(item); } for (int item : vector) { System.out.print(item); } Ok, no problem, there you go.\n\u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; for (item in arrayList) { print(item) } for (item in vector) { print(item) } 9. You can also use the withIndex library function \u0026lt;l\u0026gt;Kotlin code\u0026lt;/l\u0026gt; for ((i, value) in arr.withIndex()) { println(“the element at $i is $value”) } Usually you don’t need the withIndex function for iteration.\nAnd we are done. See I told you this will be very easy and interesting.\n","tags":["Kotlin"],"title":"Kotlin ‘For’ loop"},{"categories":["Blog"],"date":"January 11, 2018","permalink":"https://agrawalsuneet.github.io/blogs/when-operator-in-kotlin/","section":"blogs","summary":"when operator is a replacement of switch operator in other languages.\nwhen operator matches its argument with all the branches until it matches with anyone, else it executes the else block.\nvar intNumber = 10 when (intNumber) { 1 -\u0026gt; print(\u0026#34;value is 1\u0026#34;) 2 -\u0026gt; print(\u0026#34;value is 2\u0026#34;) else -\u0026gt; { print(\u0026#34;value of intNumber is neither 1 nor 2\u0026#34;) } } It can be used as an expression where the value of the satisfied branch becomes the value of the overall expression.\nfun calculateAreaOfCircle(radius: Float): Float { return (22 * radius * radius) / 7 } fun calculateAreaOfSquare(sideLength: Float): Float { return (sideLength * sideLength) } fun calculateArea(shape: Shape) : Float { var area = when (shape) { is Circle -\u0026gt; calculateAreaOfCircle( radius = 6f) is Square -\u0026gt; calculateAreaOfSquare(sideLength = 10f) else -\u0026gt; { print(\u0026#34;invalid shape\u0026#34;) return 0f } } //use area for further use return area } In the above example, based on the shape type, the overall expression is replaced with the satisfied branch.\nOr it can be used as a statement where the satisfied block’s statements will be performed.\nvar count = 100 when (count) { in 0 until 100 -\u0026gt; { //count is between 1 to 99 count++ } else -\u0026gt; { //count is greater than 99 //set it to 0 count = 0 } } The else branch is evaluated if none of the other branch conditions is satisfied. If when is used as an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions.\nval boolValue : Boolean = false when (boolValue) { false -\u0026gt; { print(\u0026#34;value is false\u0026#34;) } true -\u0026gt; { print(\u0026#34;value is true\u0026#34;) } } The branch conditions may be combined with a comma (,)\nval value = 100 when (value) { 0, 1 -\u0026gt; print(\u0026#34;x == 0 or x == 1\u0026#34;) !in 10..20, !in 30..40 -\u0026gt; { print(\u0026#34;not in 10 to 20 and 30 to 40\u0026#34;) } else -\u0026gt; print(\u0026#34;otherwise\u0026#34;) } We can also check a value for being in or !in a range or a collection.\nval value = 21 val initialPrimeNumbers = intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47) when (value) { in 10..20 -\u0026gt; print(\u0026#34;in 10 to 20\u0026#34;) !in 30 until 40 -\u0026gt; print(\u0026#34;not in 30 to 39\u0026#34;) in initialPrimeNumbers -\u0026gt; print(\u0026#34;exist in array\u0026#34;) else -\u0026gt; print(\u0026#34;not present anywhere\u0026#34;) } Another possibility is to check that a value is or !is of a particular type.\nval shape : Shape = Circle() when (shape) { is Circle -\u0026gt; print(\u0026#34;shape is a Circle class object\u0026#34;) is Square -\u0026gt; print(\u0026#34;shape is a Square class object\u0026#34;) else -\u0026gt; { print(\u0026#34;invalid shape\u0026#34;) } } when can also be used as a replacement for an if-else-if chain. If no argument is supplied, the branch conditions are simply boolean expressions, and a branch is executed when its condition is true\nval num = 10 when { isPrime(num) -\u0026gt; print(\u0026#34;num is a prime number\u0026#34;) isComposite(num) -\u0026gt; print(\u0026#34;num is a composite number\u0026#34;) else -\u0026gt; { print(\u0026#34;num is neither prime nor composit\u0026#34;) } } ","tags":["Kotlin"],"title":"when operator in Kotlin"},{"categories":["Blog"],"date":"November 24, 2017","permalink":"https://agrawalsuneet.github.io/blogs/in-operator-in-kotlin/","section":"blogs","summary":"‘in’ operator in Koltin is used to check the existence of particular variable or property in a Range or Collection whereas a ‘!in’ operator is just a not of ‘in’ operator and returns true if the condition is false. It can also be used to iterate over a range or collection.\n1. ‘in’ operator in ‘if’ condition val count = 5; if (count in 1..10 \u0026amp;\u0026amp; count !in 5..7) { print(“Number is between range 1 to 10 but not between 5 to 7”) } val array: IntArray = intArrayOf(1, 2, 3, 4, 5) if (count in array) { print(“Number is present in property array”) } 2. ‘in’ operator in ‘when’ condition when (count) { in 11..20 -\u0026gt; print(“Number is between 10 and 20 including both”) !in 21..30 -\u0026gt; print(“Number is not between 21 to 30”) in array -\u0026gt; print(“Number is present in property array”) !in array -\u0026gt; print(“Number is not present in property array”) } 3. ‘in’ operator in ‘for’ loop for (item in 1..10){ print(“iterates loop from 1 to 10”) } for (item in array){ print(“iterates all items in array”) } ","tags":["Kotlin"],"title":"‘in’ operator in Kotlin"},{"categories":["Blog"],"date":"November 23, 2017","permalink":"https://agrawalsuneet.github.io/blogs/typecheck-is-and-cast-as-in-kotlin/","section":"blogs","summary":"Type check is a way of checking the type(DataType) or Class of a particular instance or variable while runtime to separate the flow for different objects. In few languages, it’s also denoted as Run Time Type Identification (RTTI).\nLet’s consider an example where we have an Interface called Shape having an abstract method as calculateArea.\ninterface Shape { fun calculateArea(): Float } We have three different classes implementing the same interface and implementing their own area calculating method according to their shapes.\nclass Circle : Shape { var radius: Float = 10.0f override fun calculateArea(): Float { return (22 * radius * radius) / 7 } } class Square : Shape { var sideLength: Float = 10.0f override fun calculateArea(): Float { return sideLength * sideLength } } class Rectangle : Shape { var length: Float = 10.0f var breadth: Float = 5.0f override fun calculateArea(): Float { return length * breadth } } Now let’s create an object with reference to the Shape interface but implementation of different classes based on some condition.\nvar shapeObject: Shape if (/* Some Condition*/) { shapeObject = Circle() } else if (/* Some Other Condition*/) { shapeObject = Square() } else { shapeObject = Rectangle() } Now if we want to tweak the properties of the variable shapeObject (radius in case of Circle, sideLength in case of Square and length and breadth in case of Rectangle), you can’t simply use them directly as the reference to that object is Shape interface.\nshapeObject.radius = 10.0f //compile time error Before accessing the properties of shapeObject one must ensure the type of variable shapeObject.\n‘is’ and ‘!is’ Operators is operator checks the type of variable and returns boolean as true if it matches the type.\nif (shapeObject is Circle) { print(\u0026#34;it’s a Circle\u0026#34;) } else if (shapeObject is Square) { print(\u0026#34;it’s a Square\u0026#34;) } else if (shapeObject is Rectangle) { print(\u0026#34;it’s a Rectangle\u0026#34;) } !is returns true if the type doesn’t matches. It’s just a not operator for is operator.\nif (shapeObject !is Circle) { print(\u0026#34;it’s not a Circle\u0026#34;) } else if (shapeObject !is Square) { print(\u0026#34;it’s not a Square\u0026#34;) } else if (shapeObject !is Rectangle) { print(\u0026#34;it’s not a Rectangle\u0026#34;) } Smart Casts In other programming languages, the variable requires an explicit casting on the variable before accessing the properties of that variable but Kotlin does a smart casting. The compiler automatically converts the variable shapeObject to a particular class reference once it’s passed through any conditional operator.\nvar area: Float = 0.0f if (shapeObject is Circle) { shapeObject.radius = 10.0f //compiles fine area = shapeObject.calculateArea() } else if (shapeObject is Square) { shapeObject.sideLength = 5.0f //compiles fine area = shapeObject.calculateArea() } else if (shapeObject is Rectangle) { shapeObject.length = 10.0f //compiles fine shapeObject.breadth = 5.0f //compiles fine area = shapeObject.calculateArea() } The compiler is sufficiently smart to know a cast to be safe if a negative check leads to a return.\nif ( shapeObject !is Circle) return shapeObject.radius = 3.0f /*compiles fine as the non Circle class reference were already returned*/ area = shapeObject.calculateArea() It even works on the right-hand side of \u0026amp;\u0026amp; and ||\n/* Automatically cast the right-hand side of \u0026amp;\u0026amp; to Circle */ if (shapeObject is Circle \u0026amp;\u0026amp; shapeObject.radius \u0026gt; 5.0f){ print(\u0026#34;Circle with radius more than 5.0\u0026#34;) } /* Automatically cast the right hand side of || to Sqaure */ if (shapeObject !is Square || shapeObject.sideLength \u0026lt; 3.0f){ print(\u0026#34;Either not square or is a square with side length less than 3.0f\u0026#34;) } it even works with when conditions or while loop\nwhen(shapeObject){ is Circle -\u0026gt; shapeObject.radius = 3.0f is Square -\u0026gt; shapeObject.sideLength = 4.0f is Rectangle -\u0026gt; { shapeObject.length = 5.0f shapeObject.breadth = 6.0f } else -\u0026gt; print(\u0026#34;Undefined type\u0026#34;) } var count = 0 while (count \u0026lt; 5 \u0026amp;\u0026amp; shapeObject is Circle){ shapeObject.radius = count.toFloat() //compiles fine area += shapeObject.calculateArea() } Note that smart casts don’t work when the compiler can’t guarantee that the variable can’t change between the check and the usage.\nMore specifically, smart casts are applicable according to the following rules:\nval local variables — always val properties — if the property is private or internal or the check is performed in the same module where the property is declared. Smart casts aren’t applicable to open properties or properties that have custom getters var local variables — if the variable is not modified between the check and the usage and is not captured in a lambda that modifies it var properties — never (because the variable can be modified at any time by other code). Explicit Cast operator ‘as’ as operator works as other languages cast operators which casts the object to another object with particular reference.\nvar otherShapeObject = shapeObject as Circle or the nullable type object can only be cast to a new nullable reference type object.\nvar nullableShapeObject : Circle? = shapeObject as Circle? The above explicit cast is unsafe as it can throw an exception if the cast is not possible. That’s why as operator called as unsafe cast operator.\nInstead, we can use a safe cast operator as? where it assigns a null value if the cast is not possible without throwing an exception.\nvar safeCastObject : Circle? = shapeObject as? Circle ","tags":["Kotlin"],"title":"TypeCheck (‘is’) and Cast (‘as’) in Kotlin"},{"categories":["Blog"],"date":"November 13, 2017","permalink":"https://agrawalsuneet.github.io/blogs/safe-calls-vs-null-checks-in-kotlin/","section":"blogs","summary":"In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references). For example, a normal property can\u0026rsquo;t hold a null value and will show a compile error.\nvar variable : CustomClass = CustomClass() variable = null //compilation error Instead, we can add a ? after the data type of that property which declares that variable as a nullable property\nvar nullableVariable : CustomClass? = CustomClass() nullableVariable = null //works fine In any case, the nullable property requires a null check every time before accessing that property or requires a confirmation from the developer that the estimation of that property won\u0026rsquo;t be null while accessing it.\nvariable.someMethodCall() //works fine as the compiler is sure that //the variable can\u0026#39;t be null nullableVariable.someMethodCall() //will highlight compilation error //as compiler is not sure as //nullVariable can be null. There are still few techniques for using or accessing the nullable variable. One of them is safe call ?. and another one is null check !! but before figuring out the difference among both, let\u0026rsquo;s understand what they are in detail first.\nExplicit Null Check This is the old pattern that we use in every other language, checking the variable if its null or not.\nif ( null != nullableVariable) { nullableVariable.someMethodCall() } else { // fallback flow } Note this exclusive works where \u0026rsquo;nullableVariable\u0026rsquo; is immutable (i.e. a local property which can\u0026rsquo;t be altered between the check and the utilization or a member \u0026lsquo;val\u0026rsquo; which has a backing field and is not overridable), else it may happen that \u0026rsquo;nullableVariable\u0026rsquo; changes to null after the check.\nIf it\u0026rsquo;s a mutable property, the explicit null check won\u0026rsquo;t work and the compiler will show the below compilation error.\nSmart cast to CustomClass is impossible, because nullableVariable is a mutable property that could have been changed by this time. Safe Calls (?.) Another way of using a nullable property is safe call operator ?.\nThis calls the method if the property is not null or returns null if that property is null without throwing an NPE (null pointer exception).\nnullableVariable?.someMethodCall() Safe calls are useful in chains. For example, if Bob, an Employee, may be assigned to a Department (or not), that in turn may have another Employee as a department head, then to obtain the name of Bob\u0026rsquo;s department head (if any), we write the following\nval departmentHead = bob?.department?.head?.name Such a chain returns null if any of the properties in it is null.\nTo perform a certain operation only for non-null values, you can use the safe call operator together with let\nval listWithNulls: List\u0026lt;String?\u0026gt; = listOf(\u0026#34;A\u0026#34;, null) for (item in listWithNulls) { item?.let { println(it) } // prints A and ignores null } Elvis Operator (?:) This one is similar to safe calls except the fact that it can return a non-null value if the calling property is null even\nval result = nullableVariable?.someMethodCall() ?: fallbackIfNullMethodCall() The Elvis operator will evaluate the left expression and will return it if it\u0026rsquo;s not null else will evaluate the right side expression. Please note that the right side expression will only be called if the left side expression is null.\nNote that, since throw and return are expressions in Kotlin, they can also be used on the right-hand side of the Elvis operator. This can be very handy, for example, for checking function arguments\nfun foo(node: Node): String? { val parent = node.getParent() ?: return null val name = node.getName() ?: throw IllegalArgumentException(\u0026#34;name expected\u0026#34;) // … } The !! Operator This operator is used to explicitly tell the compiler that the property is not null and if it\u0026rsquo;s null, please throw a null pointer exception (NPE)\nnullableVariable!!.someMethodCall() this code will work fine if \u0026rsquo;nullableVariable\u0026rsquo; is not null else it will throw an NPE.\nDifference between ?. and !! The basic difference while using ?. and !! is if you want to separate a normal flow of var property having a \u0026rsquo;non-null\u0026rsquo; value with \u0026rsquo;null\u0026rsquo; value flow use ?. But if you are sure that the var property value is not null use !! instead of ?. Also, ?. can be used to return or throw a different kind of exceptions using ?: at the end of the expression but !! will only throw an NPE. ","tags":["Kotlin"],"title":"Safe calls(?.) vs Null checks(!!) in Kotlin"},{"categories":["Blog"],"date":"November 10, 2017","permalink":"https://agrawalsuneet.github.io/blogs/lateinit-property-in-kotlin/","section":"blogs","summary":"There can be two ways to declare and initialize a var property\nvar variable : CustomClass = CustomClass() or var variable : CustomClass? = null The first property is initialized while declaration itself and doesn’t require a null check (?.) while using it.\nBut in the second type, the property is initialized with a null value and will require a null check (?.) always while using it.\nvariable?.someMethodCall() //or variable!!.someMethodCall() There can be a use case where we don’t want to initialize the property while declaration but also at the same time we don’t want a null check on that property every time as we are sure that while using that property, it’s value will be not null for sure. Conditions like initialization of property via dependency injection or in a setup method of unit test.\nTo handle this kind of cases, we can mark the property with the ‘lateinit’ modifier\nlateinit var variable : CustomClass the property ‘variable’ can be initialized later in the constructor or in any method before accessing it. Also, it doesn’t require a null check (!!) every time while using it.\nvariable = CustomClass() variable.someMethodCall() Limitations of Late-Initialized Properties lateinit can only be used with var properties declared inside the body of class (not in the primary constructor). It can only be used when the property does not have a custom getter or setter. The type of the property must be non-null, and it must not be a primitive type. Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn’t been initialized. ","tags":["Kotlin"],"title":"lateinit Property in Kotlin"},{"categories":["Blog"],"date":"November 7, 2017","permalink":"https://agrawalsuneet.github.io/blogs/higher-order-functions-in-kotlin/","section":"blogs","summary":"What is a higher-order function? In Kotlin, a function can be passed as a parameter or can be returned from a function, the function which does the same is known as a higher-order function. In other words, a higher-order function is a function that takes functions as parameters or returns a function.\nLet’s take an example fun \u0026lt;T\u0026gt; ArrayList\u0026lt;T\u0026gt;.filterOnCondition(condition: (T) -\u0026gt; Boolean): ArrayList\u0026lt;T\u0026gt;{ val result = arrayListOf\u0026lt;T\u0026gt;() for (item in this){ if (condition(item)){ result.add(item) } } return result } in the above code,\nthis defines the template type over which the operation will be performed. There can be multiple templates defined separated by , which can be used within the same higher-order function. The multiple template definition will look like \u0026lt;T, R, S\u0026gt;\nArrayList.filterOnCondition this defines the method name as filterOnCondition which be called on an ArrayList object of the template class.\ncondition: (T) -\u0026gt; Boolean this defines a method which filterOnCondition accepts as an argument. That method name is denoted as condition which takes the template class object as an argument and return a Boolean object.\n: ArrayList this defines the return type of this(filterOnCondition) function which is an object of ArrayList of the template class in this case.\n{ val result = arrayListOf\u0026lt;T\u0026gt;() for (item in this){ if (condition(item)){ result.add(item) } } return result } this defines the body of the higher-order function which creates a new object of ArrayList of the template class and on each element of calling ArrayList object, it calls the condition method based on which it add the same item in result ArrayList and returns the result object.\nnow let’s define a conditioning method\nfun isMultipleOf (number: Int, multipleOf : Int): Boolean{ return number % multipleOf == 0 } the above method checks if the passed first argument is a multiple of another passed argument and returns a Boolean value.\nNow let’s call the higher-order function with this condition\nvar list = arrayListOf\u0026lt;Int\u0026gt;() for (number in 1..10){ list.add(number) } var resultList = list.filterOnCondition { isMultipleOf(it, 5) } The above code will filter the list object with the multiples of 5 and returns a new ArrayList object having 5 and 10 in it.\nThe last line of above code can be replaced with Lambda expression also.\nThe below two lines will do the same as the last line of above code snippet doing.\nvar resultList = list.filterOnCondition { it -\u0026gt; it % 5 == 0 } or var resultList = list.filterOnCondition { it % 5 == 0 } The same method can be called for any other data type also.\nvar listOfStr = arrayListOf\u0026lt;String\u0026gt;() listOfStr.add(\u0026#34;Hello\u0026#34;) listOfStr.add(\u0026#34;World\u0026#34;) listOfStr.add(\u0026#34;How\u0026#34;) listOfStr.add(\u0026#34;are\u0026#34;) listOfStr.add(\u0026#34;you\u0026#34;) var modifiedList = listOfStr.filterOnCondition { it.contains(\u0026#34;e\u0026#34;) } In this case the modifiedList will be an ArrayList of String type having two object “Hello” and “are” in it.\n","tags":["Kotlin"],"title":"Higher-order functions in Kotlin"},{"categories":["Blog"],"date":"August 5, 2017","permalink":"https://agrawalsuneet.github.io/blogs/backing-field-in-kotlin/","section":"blogs","summary":"What is Backing Field ? Backing field is an autogenerated field for any property which can only be used inside the accessors(getter or setter) and will be present only if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier. This backing field is used to avoid the recursive call of an accessor which ultimately prevents the StackOverflowError.\nWhat is the need for Backing field ? have a look at the below Kotlin code\nvar selectedColor: Int = someDefaultValue { get() = selectedColor set(value) { this.selectedColor = value doSomething() } } The above code is calling the getter in a recursive manner if we try to get the value of selectedColor. when we call selectedColor, it calls the getter again inside the getter which might end with a StackOverflowError.\nSimilar way, when we try to set the value of selectedColor it calls the same setter in a recursive way as ‘this.selectedColor’ calls the setter again from inside a setter method.\nHow to use Backing field ? Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier.\nReplace the variable with the keyword field inside getter and setter\nvar selectedColor: Int = someDefaultValue get() = field set(value) { field = value } Limitations while using Backing field The field identifier can only be used in the accessors of the property. A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier. For example, in the following case there will be no backing field:\nval isEmpty: Boolean get() = this.size == 0 ","tags":["Kotlin"],"title":"Backing Field in Kotlin"}]