<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Suleman Afzal on Medium]]></title>
        <description><![CDATA[Stories by Suleman Afzal on Medium]]></description>
        <link>https://medium.com/@sulemanafzal?source=rss-a50e1d134cbf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7bG0d6fCmxQOMYPT</url>
            <title>Stories by Suleman Afzal on Medium</title>
            <link>https://medium.com/@sulemanafzal?source=rss-a50e1d134cbf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:10:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sulemanafzal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering MVVM Architecture in Android with Kotlin — Beginner Friendly Guide In Urdu Roman]]></title>
            <link>https://medium.com/@sulemanafzal/mastering-mvvm-architecture-in-android-with-kotlin-beginner-friendly-guide-in-urdu-roman-399571ebf6be?source=rss-a50e1d134cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/399571ebf6be</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Suleman Afzal]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 19:57:57 GMT</pubDate>
            <atom:updated>2025-09-17T19:57:57.650Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering MVVM Architecture in Android with Kotlin — Beginner Friendly Guide In Urdu Roman</h3><h3><strong>Introduction</strong></h3><p>Aaj ke Android development me <strong>MVVM (Model-View-ViewModel)</strong> ek popular architecture pattern hai jo clean aur maintainable code likhne me help karta hai.<br> Is article me hum MVVM ko step by step samjhenge aur ek small project example ke through implement karenge.</p><h3>Architecture Diagram Example:</h3><p>Diagram important hai taake readers ko visual samajh aaye.<br> Aap <a href="https://excalidraw.com/">excalidraw.com</a> ya Canva me diagram bana sakte ho.</p><h3>Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2IzF19JFbH1KpELfm5e2A.png" /></figure><p><strong>MVVM Flow:</strong></p><p>UI (Activity/Fragment) ←&gt; ViewModel ←&gt; Repository ←&gt; API/Database</p><h3>📌 <strong>What is ViewModel?</strong></h3><p>ViewModel ek class hoti hai jo UI aur Data ko connect karti hai.<br> Ye <strong>lifecycle-aware</strong> hoti hai, iska matlab ye Activity/Fragment ke destroy hone par bhi data ko retain kar sakti hai.<br>✅ Why Use ViewModel?</p><ul><li><strong>Lifecycle Awareness:</strong><br> Configuration change (screen rotate hone par) data lose nahi hota.</li><li><strong>No Memory Leaks:</strong><br> ViewModel UI se directly bind nahi hota.</li><li><strong>Clean Architecture:</strong><br> ViewModel UI logic ko hold karta hai, data ko fetch karne ka kaam repository ko deta hai.</li><li><strong>LiveData/StateFlow Support:</strong><br> UI me automatic updates milte hain jab data change hota hai.</li></ul><h3>🔧 Example: Simple ViewModel</h3><pre>class ProductViewModel(private val repository: ProductRepository) : ViewModel() {<br><br>    private val _products = MutableLiveData&lt;List&lt;Product&gt;&gt;()<br>    val products: LiveData&lt;List&lt;Product&gt;&gt; get() = _products<br><br>    fun fetchProducts() {<br>        viewModelScope.launch {<br>            try {<br>                val result = repository.getProducts()<br>                _products.postValue(result)<br>            } catch (e: Exception) {<br>                // error handle karo<br>            }<br>        }<br>    }<br>}</pre><p>🌀 <strong>Key Points About ViewModel:</strong></p><ul><li><strong>viewModelScope.launch {}</strong><br> Ye coroutine ka use karta hai jo automatically cancel ho jata hai jab ViewModel destroy hota hai.</li><li><strong>LiveData</strong><br> UI ko data observe karne ke liye use hota hai. Jab data update hota hai to UI automatically refresh ho jata hai.</li><li><strong>Separation of Concerns</strong><br> ViewModel me koi UI code nahi hota. Sirf data aur business logic hoti hai.</li></ul><h3>📌 <strong>What is Repository?</strong></h3><p>Repository ek <strong>data handling layer</strong> hoti hai jo aapke data sources (API, Database, SharedPreferences, etc.) ko manage karti hai.</p><p>Ye ek <strong>single source of truth</strong> provide karti hai — ViewModel ya UI ko ye nahi pata hota ke data kaha se aa raha hai (API se ya Database se), bas Repository ko call karta hai aur data mil jata hai.</p><p>✅ Why Use Repository?</p><ul><li><strong>Separation of Concerns:</strong><br> UI aur data fetching ka code alag rehta hai.</li><li><strong>Easy Maintenance:</strong><br> Agar kal ko API change ho, aap sirf repository me changes karoge.</li><li><strong>Testing Friendly:</strong><br> Mock repository use karke ViewModel ko easily test kar sakte ho.</li><li><strong>Offline + Online Handling:</strong><br> Repository me logic likh sakte ho ke agar internet nahi hai to Room database se data fetch ho.</li></ul><h3>🔧 Example: Repository with API</h3><h4>1. API Interface</h4><pre>interface ProductApi {<br>    @GET(&quot;products&quot;)<br>    suspend fun getProducts(): List&lt;Product&gt;<br>}</pre><h4>2. Repository Implementation</h4><pre>class ProductRepository(private val api: ProductApi) {<br><br>    suspend fun getProducts(): List&lt;Product&gt; {<br>        // Yahan aap API call kar rahe ho<br>        return api.getProducts()<br>    }<br>}</pre><h3>🔧 Example: Repository with API + Database (Advanced)</h3><pre>class ProductRepository(<br>    private val api: ProductApi,<br>    private val dao: ProductDao<br>) {<br><br>    suspend fun getProducts(): List&lt;Product&gt; {<br>        // Pehle local DB se data lao<br>        val localData = dao.getProducts()<br>        if (localData.isNotEmpty()) {<br>            return localData // agar DB me data hai to wahi return karo<br>        }<br><br>        // Agar local data empty hai to API call karo<br>        val remoteData = api.getProducts()<br>        dao.insertProducts(remoteData) // DB me save karo<br>        return remoteData<br>    }<br>}</pre><h3>🔧 UI Example (View + ViewModel Connection)</h3><pre>class ProductFragment : Fragment() {<br><br>    private val viewModel: ProductViewModel by viewModels()<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br><br>        // Observe data<br>        viewModel.products.observe(viewLifecycleOwner) { productList -&gt;<br>            // RecyclerView update karo<br>        }<br><br>        // Fetch products<br>        viewModel.fetchProducts()<br>    }<br>}</pre><h3>🔑 Summary Table (Repository vs ViewModel)</h3><pre>| **Component**  | **Role**                         | **Contains**                         | **Talks To**    |<br>| -------------- | -------------------------------- | ------------------------------------ | --------------- |<br>| **Repository** | Data Source Manager              | API calls, DB queries, caching logic | API, Database   |<br>| **ViewModel**  | Bridge between UI and Repository | LiveData/StateFlow, business logic   | Repository &amp; UI |</pre><p><strong>In Short:</strong></p><ul><li><strong>Repository</strong> = Data ka boss (API/DB ka source handle karta hai)</li><li><strong>ViewModel</strong> = Data ka manager (UI ko data deta hai, lifecycle safe rehta hai)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=399571ebf6be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop a RecyclerView in Android using Kotlin.]]></title>
            <link>https://medium.com/@sulemanafzal/develop-a-recyclerview-in-android-using-kotlin-e50376a3ad36?source=rss-a50e1d134cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e50376a3ad36</guid>
            <dc:creator><![CDATA[Suleman Afzal]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 10:33:43 GMT</pubDate>
            <atom:updated>2023-11-22T10:33:43.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*P0jDjJwdKU8dIXm6apEDcA.png" /><figcaption>What is RecyclerView?</figcaption></figure><p>RecyclerView is a powerful and flexible widget available in the Android Support Library. It is used for displaying a scrollable list or grid of items in your Android application. Unlike the older ListView, RecyclerView is more customizable and efficient, especially when dealing with large datasets.</p><h4>Key Components:</h4><ol><li>Adapter:</li></ol><ul><li>The RecyclerView requires an adapter to manage the data and create views for each item in the dataset.</li><li>You need to create a custom adapter by extending RecyclerView.Adapter and override methods like onCreateViewHolder, onBindViewHolder, and getItemCount.</li></ul><p>2. ViewHolder:</p><ul><li>ViewHolder represents each item in the RecyclerView.</li><li>It holds references to the views that represent the item and is responsible for binding data to those views.</li></ul><p>3. LayoutManager:</p><ul><li>LayoutManager is responsible for positioning items in the RecyclerView.</li><li>It can be a LinearLayoutManager (for displaying items in a vertical or horizontal list), GridLayoutManager (for displaying items in a grid), or a custom layout manager.</li></ul><h3>Initialize ViewBinding</h3><ul><li>Open app level build.gradle file</li><li>In android section add this code</li></ul><pre>buildFeatures {<br>    viewBinding = true<br>}</pre><h4>LayoutManager Types:</h4><ol><li>LinearLayoutManager:</li></ol><ul><li>Arranges items in a vertical or horizontal scrolling list.</li></ul><pre>binding.recyclerView.layoutManager = LinearLayoutManager(this)<br>binding.recyclerView.hasFixedSize()<br><br>binding.recyclerView.adapter = RvAdapter(listofitem, this)</pre><p>2. GridLayoutManager:</p><ul><li>Arranges items in a grid.</li></ul><pre>binding.recyclerView.layoutManager = GridLayoutManager(this, 2)<br>        binding.recyclerView.hasFixedSize()<br><br>        binding.recyclerView.adapter = RvAdapter(listofitem, this)</pre><p>3. StaggeredGridLayoutManager:</p><ul><li>Similar to GridLayoutManager, but items can have variable sizes.</li></ul><pre>binding.recyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.HORIZONTAL)<br>        binding.recyclerView.hasFixedSize()<br><br>        binding.recyclerView.adapter = RvAdapter(listofitem, this)</pre><h3><strong>Here are the dependencies for SSP and SDP in your Android project:</strong></h3><pre>implementation (&quot;com.intuit.ssp:ssp-android:1.1.0&quot;)<br>implementation (&quot;com.intuit.sdp:sdp-android:1.1.0&quot;)</pre><ol><li>Layout (activity_main.xml):</li></ol><pre> &lt;androidx.recyclerview.widget.RecyclerView<br>        android:id=&quot;@+id/recyclerView&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br></pre><pre><br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;com.google.android.material.card.MaterialCardView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:layout_margin=&quot;@dimen/_6sdp&quot;<br>    app:cardCornerRadius=&quot;@dimen/_12sdp&quot;<br>  &gt;<br><br>    &lt;androidx.constraintlayout.widget.ConstraintLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:background=&quot;#BDE2FF&quot;<br>        android:orientation=&quot;vertical&quot;<br>        android:padding=&quot;@dimen/_10sdp&quot;&gt;<br><br>        <br>        &lt;TextView<br>            android:id=&quot;@+id/tv_name&quot;<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_marginStart=&quot;13dp&quot;<br>            android:layout_marginEnd=&quot;13dp&quot;<br>            android:text=&quot;name&quot;<br>            android:textSize=&quot;@dimen/_18ssp&quot;<br>            android:textStyle=&quot;bold&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/tv_addres&quot;<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;addres&quot;<br>            android:textSize=&quot;@dimen/_16ssp&quot;<br>            android:layout_marginTop=&quot;@dimen/_12sdp&quot;<br>            android:textStyle=&quot;normal&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;@+id/tv_name&quot;<br>            app:layout_constraintStart_toStartOf=&quot;@+id/tv_name&quot;<br>            app:layout_constraintTop_toBottomOf=&quot;@+id/tv_name&quot; /&gt;<br>    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;<br><br><br>&lt;/com.google.android.material.card.MaterialCardView&gt;</pre><ol><li>Adapter (CustomAdapter.kt):</li></ol><pre><br>class RvAdapter(private val personList: MutableList&lt;RvModel&gt;) :<br>    RecyclerView.Adapter&lt;RvAdapter.RvViewHolder&gt;() {<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RvViewHolder {<br>        val binding = RvItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)<br>        return RvViewHolder(binding)<br>    }<br><br>    override fun getItemCount(): Int = personList.size<br><br>    override fun onBindViewHolder(holder: RvViewHolder, position: Int) {<br>        val currentItem = personList[position]<br>        holder.bind(currentItem)<br>    }<br><br>    class RvViewHolder(private val binding: RvItemBinding) :<br>        RecyclerView.ViewHolder(binding.root) {<br><br>        fun bind(item: RvModel) {<br>            binding.tvName.text = item.name<br>            binding.tvAddres.text = item.addres<br>        }<br>    }<br>}</pre><ol><li>Activity (MainActivity.kt):</li></ol><pre><br>class RecyclerViewActivity : AppCompatActivity() {<br>    lateinit var binding: ActivityRecyclerViewBinding<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        binding = ActivityRecyclerViewBinding.inflate(layoutInflater)<br>        setContentView(binding.root)<br><br>        val listofitem = mutableListOf&lt;RvModel&gt;(<br>            RvModel(&quot;John Doe&quot;, &quot;123 Main Street, Sydney, Australia&quot;),<br>            RvModel(&quot;Alice Johnson&quot;, &quot;456 Oak Avenue, Melbourne, Australia&quot;),<br>            RvModel(&quot;Bob Williams&quot;, &quot;789 Pine Road, Brisbane, Australia&quot;),<br>            RvModel(&quot;Eva Davis&quot;, &quot;321 Maple Lane, Perth, Australia&quot;),<br>            RvModel(&quot;Michael Smith&quot;, &quot;567 Cedar Street, Adelaide, Australia&quot;),<br>            RvModel(&quot;Sophia Brown&quot;, &quot;890 Birch Boulevard, Canberra, Australia&quot;),<br>            RvModel(&quot;David Miller&quot;, &quot;234 Elm Court, Karachi, Pakistan&quot;),<br>            RvModel(&quot;Olivia Wilson&quot;, &quot;876 Walnut Drive, Cape Town, Africa&quot;),<br>            RvModel(&quot;James Taylor&quot;, &quot;543 Cherry Circle, Mumbai, India&quot;),<br>            RvModel(&quot;Emma Davis&quot;, &quot;987 Spruce Place, Auckland, New Zealand&quot;),<br>            RvModel(&quot;Liam White&quot;, &quot;654 Pinecrest Avenue, Wellington, New Zealand&quot;)<br>        )<br><br><br>        //StaggeredGridLayoutManager<br>        /*binding.recyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.HORIZONTAL)<br>        */<br>        // GridLayoutManager<br>        /*   binding.recyclerView.layoutManager =  GridLayoutManager(this,2)//2 row<br>   */<br>        //LinearLayout Manager<br>        binding.recyclerView.layoutManager = LinearLayoutManager(this)<br><br>        binding.recyclerView.hasFixedSize()<br><br>        binding.recyclerView.adapter = RvAdapter(listofitem)<br><br><br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e50376a3ad36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin for Beginners]]></title>
            <link>https://medium.com/@sulemanafzal/kotlin-for-beginners-156e6cdfd24e?source=rss-a50e1d134cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/156e6cdfd24e</guid>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[kotlin-for-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Suleman Afzal]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 09:17:33 GMT</pubDate>
            <atom:updated>2023-07-05T09:17:33.717Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>What is Kotlin?</strong></blockquote><p>Kotlin is a modern programming language developed by JetBrains. It is designed to be fully interoperable with Java, which means that you can use Kotlin alongside your existing Java codebase. Kotlin aims to improve developer productivity and offers concise syntax, null safety, and functional programming capabilities.</p><p>Setting Up Kotlin To get started with Kotlin, you need to set up the Kotlin compiler and development environment. Here’s a step-by-step guide:</p><ol><li>Install Java Development Kit (JDK) if you haven’t already.</li><li>Download and install IntelliJ IDEA, which is an Integrated Development Environment (IDE) that provides excellent support for Kotlin.</li><li>Open IntelliJ IDEA and create a new Kotlin project.</li></ol><p>Hello World in Kotlin Let’s start by writing a simple “Hello, World!” program in Kotlin:</p><h4>fun main() {<br> println(“Hello, World!”)<br>}</h4><p>In Kotlin, the entry point of a program is the main function. The above code declares a main function that takes no arguments and prints &quot;Hello, World!&quot; using the println function.</p><blockquote>Variables and Data Types</blockquote><p>In Kotlin, you declare variables using the val (immutable) or var (mutable) keywords. Kotlin provides type inference, so you don&#39;t always need to explicitly specify the type.</p><p>Here&#39;s an example:</p><h4>fun main() {<br> val message = “Hello, Kotlin!” // immutable variable<br> var count = 10 // mutable variable</h4><h4>println(message)<br> count = 20<br> println(count)<br>}</h4><p>In this example, message is an immutable variable with an inferred type of String, and count is a mutable variable with an inferred type of Int. Note that you can reassign a value to a mutable variable (count in this case), but you cannot do the same with an immutable variable (message).</p><blockquote>Functions:</blockquote><p>Functions in Kotlin are declared using the fun keyword. Here&#39;s an example of a function that takes two integers and returns their sum:</p><h4>fun addNumbers(a: Int, b: Int): Int {<br> return a + b<br>}</h4><h4>fun main() {<br> val result = addNumbers(3, 5)<br> println(“The sum is: $result”)<br>}</h4><p>In this example, the addNumbers function takes two parameters of type Int and returns their sum. The main function calls addNumbers with arguments 3 and 5 and prints the result.</p><blockquote>Control Flow</blockquote><p>Kotlin provides various control flow structures like if, when, for, and while. Here&#39;s an example that demonstrates the usage of if and when:</p><h4>fun main() {<br> val number = 5</h4><h4>if (number &gt; 0) {<br> println(“Positive”)<br> } else if (number &lt; 0) {<br> println(“Negative”)<br> } else {<br> println(“Zero”)<br> }</h4><h4>val day = 2</h4><h4>when (day) {<br> 1 -&gt; println(“Monday”)<br> 2 -&gt; println(“Tuesday”)<br> in 3..5 -&gt; println(“Weekday”)<br> else -&gt; println(“Weekend”)<br> }<br>}</h4><p>In this example, the if statement checks whether number is positive, negative, or zero, and prints the corresponding message. The when expression matches the value of day and prints the appropriate day of the week.</p><blockquote>Classes and Objects</blockquote><p>Kotlin is an object-oriented programming language, and it supports classes and objects. Here’s an example of defining a class and creating objects from it:</p><h4>class Person(val name: String, val age: Int) {<br> fun speak() {<br> println(“My name is $name and I am $age years old.”)<br> }<br>}</h4><h4>fun main() {<br> val person1 = Person(“John”, 25)<br> val person2 = Person(“Sarah”, 30)</h4><h4>person1.speak()<br> person2.speak()<br>}</h4><p>In this example, we define a Person class with properties name and age. The speak() function prints a message using the property values. In the main() function, we create two Person objects, initialize them with different values, and call the speak() function on each object.</p><blockquote>Null Safety</blockquote><p>Kotlin has built-in null safety features to help prevent null pointer exceptions. In Kotlin, you must explicitly specify whether a variable can hold null by using the nullable type modifier (?).</p><p>Here&#39;s an example:</p><h4>fun main() {<br> val name: String = “John”<br> val nullableName: String? = null</h4><h4>println(name.length)<br> // println(nullableName.length) // Compilation error</h4><h4>if (nullableName != null) {<br> println(nullableName.length)<br> } else {<br> println(“Name is null”)<br> }</h4><h4>val length = nullableName?.length<br> println(length)<br>}</h4><p>In this example, we have a variable name of type String and a nullable variable nullableName of type String?. We can directly access the length property of name because it is guaranteed to be non-null. However, we cannot directly access the length property of nullableName because it can be null. To safely access the property, we use the safe call operator (?.), which returns the length if nullableName is not null or null otherwise.</p><blockquote>Collections</blockquote><p>Kotlin provides a rich set of collection types, such as lists, sets, and maps. Here’s an example that demonstrates the usage of some collection types:</p><h4>fun main() {<br> // List<br> val numbers = listOf(1, 2, 3, 4, 5)<br> println(numbers)</h4><h4>// Set<br> val uniqueNumbers = setOf(1, 2, 3, 4, 5, 5)<br> println(uniqueNumbers)</h4><h4>// Map<br> val fruits = mapOf(“apple” to 5, “banana” to 3, “orange” to 2)<br> println(fruits)</h4><h4>// Accessing elements<br> println(numbers[0])<br> println(fruits[“apple”])</h4><h4>// Iterating over a list<br> for (number in numbers) {<br> println(number)<br> }</h4><h4>// Iterating over a map<br> for ((fruit, quantity) in fruits) {<br> println(“$fruit: $quantity”)<br> }<br>}</h4><p>In this example, we create a list of numbers, a set of unique numbers, and a map of fruit names and quantities. We can access elements of a list or map using the indexing syntax. We can also iterate over the elements of a collection using a for loop, either by directly iterating over the collection or by using destructuring declarations for maps.</p><blockquote>Lambda Expressions</blockquote><p>Kotlin supports functional programming constructs, such as lambda expressions. Here’s an example that demonstrates the usage of lambda expressions:</p><h4>fun main() {<br> val numbers = listOf(1, 2, 3, 4, 5)</h4><h4>val evenNumbers = numbers.filter { it % 2 == 0 }<br> println(evenNumbers)</h4><h4>val squaredNumbers = numbers.map { it * it }<br> println(squaredNumbers)</h4><h4>val sum = numbers.reduce { acc, number -&gt; acc + number }<br> println(sum)<br>}</h4><p>In this example, we have a list of numbers. We use lambda expressions with higher-order functions like filter, map, and reduce. The lambda expressions define the conditions or operations to be applied to each element of the list.</p><blockquote>Inheritance and Interfaces</blockquote><p>Kotlin supports class inheritance and interfaces, allowing you to create hierarchies and define contracts.</p><p>Here’s an example:</p><h4>open class Animal(val name: String) {<br> open fun makeSound() {<br> println(“The animal makes a sound.”)<br> }<br>}</h4><h4>class Cat(name: String) : Animal(name) {<br> override fun makeSound() {<br> println(“Meow!”)<br> }<br>}</h4><h4>interface Flyable {<br> fun fly()<br>}</h4><h4>class Bird(name: String) : Animal(name), Flyable {<br> override fun makeSound() {<br> println(“Chirp chirp!”)<br> }</h4><h4>override fun fly() {<br> println(“The bird is flying.”)<br> }<br>}</h4><h4>fun main() {<br> val cat = Cat(“Whiskers”)<br> cat.makeSound()</h4><h4>val bird = Bird(“Sparrow”)<br> bird.makeSound()<br> bird.fly()<br>}</h4><p>In this example, we have an Animal class with a makeSound() function. The Cat class inherits from Animal and overrides the makeSound() function to make a different sound. The Bird class inherits from Animal and also implements the Flyable interface. It provides its own implementation for both the makeSound() function and the fly() function. In the main() function, we create instances of Cat and Bird and call their respective methods.</p><blockquote>Exception Handling</blockquote><p>Exception handling allows you to handle and recover from exceptional situations in your code. Kotlin provides a try-catch block for exception handling.</p><p>Here&#39;s an example:</p><h4>fun divide(a: Int, b: Int): Int {<br> return try {<br> a / b<br> } catch (e: ArithmeticException) {<br> println(“Error: Division by zero.”)<br> 0<br> }<br>}</h4><h4>fun main() {<br> val result1 = divide(10, 2)<br> println(“Result1: $result1”)</h4><h4>val result2 = divide(8, 0)<br> println(“Result2: $result2”)<br>}</h4><p>In this example, we have a divide() function that performs division. We use a try-catch block to handle the ArithmeticException that occurs when dividing by zero. If an exception is caught, we print an error message and return a default value (in this case, 0). In the main() function, we call divide() twice to demonstrate both scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=156e6cdfd24e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[View stub in Android]]></title>
            <link>https://medium.com/@sulemanafzal/view-stub-in-android-4a3084854960?source=rss-a50e1d134cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a3084854960</guid>
            <dc:creator><![CDATA[Suleman Afzal]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 07:49:15 GMT</pubDate>
            <atom:updated>2023-07-05T07:49:15.494Z</atom:updated>
            <content:encoded><![CDATA[<p>A view stub in Android is a lightweight, invisible container that allows you to lazily inflate and load a view hierarchy into your app’s layout at runtime. It helps improve performance by deferring the inflation of complex views until they are needed. You can add a ViewStub element to your XML layout, find it in your code, and inflate the desired view hierarchy when necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*d1wZal9hhZjTv6ao4BdO2w.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a3084854960" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[inline, noinline, crossinline, reified in kotlin with example]]></title>
            <link>https://medium.com/@sulemanafzal/inline-noinline-crossinline-reified-in-kotlin-with-example-62f6f269993e?source=rss-a50e1d134cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/62f6f269993e</guid>
            <dc:creator><![CDATA[Suleman Afzal]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 12:45:01 GMT</pubDate>
            <atom:updated>2023-07-04T12:45:01.190Z</atom:updated>
            <content:encoded><![CDATA[<h4>inline:</h4><p>The inline keyword is used to instruct the Kotlin compiler to replace the function call with the actual function body during compilation. This can improve performance by reducing the overhead of function calls. It is commonly used when working with higher-order functions or when performance optimization is desired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0MtcFUrLQpf7F0xhqSFLQ.png" /></figure><h3>noinline:</h3><p>The noinline keyword is used to indicate that a lambda parameter of a higher-order function should not be inlined. By default, lambdas passed as parameters to inline functions are also inlined. However, by marking a lambda parameter with noinline, you prevent it from being inlined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyQ0OUqwjUKCWZzHwCZDXQ.png" /></figure><h3>Crossinline:</h3><p>The crossinline keyword is used in Kotlin to enforce that a lambda parameter of an inline function cannot have non-local returns. By default, when you pass a lambda as a parameter to an inline function, it is allowed to have non-local returns, meaning you can use return statements to exit the lambda and the surrounding function. However, by marking the lambda parameter with crossinline, you prohibit non-local returns, ensuring that control flow remains within the lambda and the inline function. This ensures more predictable behavior and avoids potential issues caused by non-local returns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0t0LAzaELVOJYjZW0Dc6WA.png" /></figure><h3>reified</h3><p>the reified keyword in Kotlin is used in combination with the inline keyword to allow access to the type information of a generic parameter at runtime. By using reified, you can treat a generic type as a regular type within an inline function, enabling you to perform operations that require runtime knowledge of the type. It allows you to access properties, call functions, or use reflection on the generic type without losing type information due to type erasure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8JfWwrIPOLZsWmWZT2KuA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62f6f269993e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arithmetic & Relational Operators Kotlin]]></title>
            <link>https://medium.com/@sulemanafzal/arithmetic-relational-operators-kotlin-28d88b1aa07e?source=rss-a50e1d134cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d88b1aa07e</guid>
            <dc:creator><![CDATA[Suleman Afzal]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 08:22:33 GMT</pubDate>
            <atom:updated>2023-07-04T08:22:33.178Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zJ1XP0QZmcY9bta6q0aDw.png" /><figcaption><a href="https://www.w3schools.com/KOTLIN/kotlin_booleans.php">more…</a></figcaption></figure><blockquote>Example”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljeOkDykfI3MdHwBt53Y-A.png" /><figcaption><a href="https://www.programiz.com/kotlin-programming/operators">More</a>….</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d88b1aa07e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variables & Data Types in Kotlin]]></title>
            <link>https://medium.com/@sulemanafzal/variables-data-types-in-kotlin-e7afa96dc142?source=rss-a50e1d134cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7afa96dc142</guid>
            <dc:creator><![CDATA[Suleman Afzal]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 07:25:57 GMT</pubDate>
            <atom:updated>2023-07-04T07:25:57.889Z</atom:updated>
            <content:encoded><![CDATA[<p>Kotlin provides a concise syntax for declaring variables and supports various basic types such as Int, String, Boolean, Float, etc. Understanding how to declare and use variables, perform basic operations, and work with different data types is essential.</p><p>Example”</p><p>fun main(args:Array&lt;String&gt;){<br> println(“Variables &amp; Data Types”)</p><p>//Difference Between val and va<br> //val is used for immutable variables, whose value cannot be changed after initialization.</p><p>val name = “Smith”<br> name = “John” // Error: Val cannot be reassigned<br> println(name)</p><p>// var is used for mutable variables, whose value can be changed after initialization.<br> var age = 23<br> age = 42 // Valid: Var can be reassigned<br> println(age)</p><p>}</p><blockquote><a href="https://www.w3schools.com/KOTLIN/kotlin_data_types.php"><strong>Data Types:</strong></a><strong> </strong>Kotlin provides various data types, including:</blockquote><p>Numeric types: Byte, Short, Int, Long, Float, Double<br>Characters: Char //<br>Boolean: Boolean // true or false<br>Text: String</p><p><strong>Byte:</strong> Represents a signed 8-bit integer. It has a range from -128 to 127.<br><strong>Short</strong>: Represents a signed 16-bit integer. Its range is -32768 to 32767.<br><strong>Int</strong>: Represents a signed 32-bit integer. It has a range from -2³¹ to 2³¹ — 1.<br><strong>Long</strong>: Represents a signed 64-bit integer. Its range is -2⁶³ to 2⁶³ — 1.<br><strong>Float</strong>: Represents a single-precision 32-bit floating-point number. It can store fractional numbers and has a higher range than Int.<br><strong>Double</strong>: Represents a double-precision 64-bit floating-point number. It provides more precision and has a larger range than Float.</p><p><strong>Example:</strong></p><p>val myByte: Byte = 10<br>val myInt: Int = 100<br>val myFloat: Float = 3.14f<br>val myDouble: Double = 3.14159</p><p><strong>Character Type:</strong></p><ul><li>Char: Represents a single Unicode character. It is declared using single quotes (&#39; &#39;).</li></ul><p>Example”</p><p>val letter: Char = ‘A’<br>val symbol: Char = ‘$’</p><p><strong>String in Kotlin</strong></p><ul><li>Strings in Kotlin are declared using the String type.</li><li>They can be initialized with double quotes (&quot; &quot;) or triple quotes (&quot;&quot;&quot; &quot;&quot;&quot;) for multiline strings.</li><li>String concatenation can be done using the + operator or by using string interpolation with the $ symbol.</li><li>String interpolation allows you to embed variables or expressions directly within strings.</li><li>Kotlin provides various built-in functions and properties for working with strings, such as length, toUpperCase(), substring(), startsWith(), and more.</li><li>Escape sequences like \n, \t, \\, and \&quot; can be used to represent special characters within strings .</li><li>Kotlin provides various built-in functions and properties for working with strings, such as length, toUpperCase(), substring(), startsWith(), and <a href="https://www.w3schools.com/KOTLIN/kotlin_strings.php">more</a>…</li></ul><p>Example”</p><p>val name = “smith”<br>val age = 30<br>val message = “My name is $name and I am $age years old.”</p><p>val text = “Hello, Kotlin!”<br>println(text.length) // Output: 15<br>println(text.toUpperCase()) // Output: HELLO, KOTLIN!<br>println(text.substring(7)) // Output: Kotlin!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7afa96dc142" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello World Program In Kotlin]]></title>
            <link>https://medium.com/@sulemanafzal/hello-world-program-in-kotlin-31e5fd1a4a37?source=rss-a50e1d134cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/31e5fd1a4a37</guid>
            <dc:creator><![CDATA[Suleman Afzal]]></dc:creator>
            <pubDate>Thu, 04 May 2023 06:01:36 GMT</pubDate>
            <atom:updated>2023-05-04T06:01:36.841Z</atom:updated>
            <content:encoded><![CDATA[<pre>There is a special method/function that runs when we start running our program. Our program starts execution by calling this function. This particular method is known as the main method.<br>If you have multiple Kotlin files, the JVM looks for a file where the main method is defined and executes that method. So we need to write the main method - this is the entry point of our program.<br><br>fun main()<br>    {<br>      println(&quot;Welcome To Kotlin&quot;)<br>      println(&quot;Hello World&quot;)<br>      //prints Welcome To Kotlin and Hello World in console<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31e5fd1a4a37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrofit Api]]></title>
            <link>https://medium.com/@sulemanafzal/retrofit-api-919c8c163135?source=rss-a50e1d134cbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/919c8c163135</guid>
            <dc:creator><![CDATA[Suleman Afzal]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 09:47:54 GMT</pubDate>
            <atom:updated>2023-04-11T09:47:54.074Z</atom:updated>
            <content:encoded><![CDATA[<p>Retrofit API is a type-safe HTTP client for Android and Kotlin that makes it easier to consume RESTful web services. It allows you to easily and efficiently communicate with a server by specifying the API’s endpoints, request parameters, and response types in your Java interface. Retrofit also supports various serializers and deserializers for JSON, XML, and other data formats. This library helps to reduce the amount of boilerplate code required to interact with APIs and provides better type safety to avoid runtime errors, making it a popular choice for Android developers.</p><p>To use Retrofit API in Android Kotlin application, you can follow these simple steps:</p><p>1. Add the following dependency in build.gradle file:</p><p>implementation ‘com.squareup.retrofit2:retrofit:2.9.0’</p><p>2. Create a Retrofit client object:</p><p>val retrofit = Retrofit.Builder()</p><p>.baseUrl(“https://api.example.com/&quot;)</p><p>.addConverterFactory(GsonConverterFactory.create())</p><p>.build()</p><p>val apiService = retrofit.create(ApiService::class.java)</p><p>Here, `ApiService` is the interface representing the API endpoints.</p><p>3. Define API endpoints in `ApiService` interface:</p><p>interface ApiService {</p><p>@GET(“/users”)</p><p>fun getUsers(): Call&lt;List&lt;User&gt;&gt;</p><p>@POST(“/user”)</p><p>fun createUser(@Body user: User): Call&lt;User&gt;</p><p>}</p><p>Here, `GET` and `POST` are HTTP methods and `User` is the data model representing user information.</p><p>4. Make API calls from activity/fragment:</p><p>apiService.getUsers().enqueue(object : Callback&lt;List&lt;User&gt;&gt; {</p><p>override fun onResponse(call: Call&lt;List&lt;User&gt;&gt;, response: Response&lt;List&lt;User&gt;&gt;) {</p><p>if (response.isSuccessful) {</p><p>val userList = response.body()</p><p>// Do something with user list</p><p>}</p><p>}</p><p>override fun onFailure(call: Call&lt;List&lt;User&gt;&gt;, t: Throwable) {</p><p>// Handle failure</p><p>}</p><p>})</p><p>Here, `enqueue()` method is used to perform API call asynchronously. `onResponse()` and `onFailure()` methods are called based on API response.</p><p>Remember to add required permissions for internet access in the AndroidManifest.xml file</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=919c8c163135" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>