<?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 Sümeyra Özuğur-En on Medium]]></title>
        <description><![CDATA[Stories by Sümeyra Özuğur-En on Medium]]></description>
        <link>https://medium.com/@ozugursumeyraenglish?source=rss-a95f6db0afc9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HHgpnnNNrDTJhEhj</url>
            <title>Stories by Sümeyra Özuğur-En on Medium</title>
            <link>https://medium.com/@ozugursumeyraenglish?source=rss-a95f6db0afc9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:16:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ozugursumeyraenglish/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[Primary & Secondary Constructors]]></title>
            <link>https://towardsdev.com/primary-secondary-constructors-c61a6b9f0b6d?source=rss-a95f6db0afc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c61a6b9f0b6d</guid>
            <category><![CDATA[constructor]]></category>
            <category><![CDATA[secondary-constructor]]></category>
            <category><![CDATA[primary-constructor]]></category>
            <dc:creator><![CDATA[Sümeyra Özuğur-En]]></dc:creator>
            <pubDate>Sun, 21 May 2023 21:38:53 GMT</pubDate>
            <atom:updated>2023-05-23T17:06:45.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMUbhhYbfwoKpcigAwZocg.png" /></figure><p>There are two different types of constructors in Kotlin: primary constructor and secondary constructor.</p><pre>class Constructors { //Default primary constructor<br>    init {<br>        println(&quot;Init block&quot;)<br>    }</pre><pre>    constructor(i: Int) { //Second Construtor<br>        println(&quot;Constructor $i&quot;)<br>    }<br>}</pre><pre>//Output<br>// Init block<br>// Constructor 1</pre><pre>class Customer(var unumber:Int):User(){</pre><pre>    override fun userNumber():Int{<br>        this.unumber = 100<br>        return this.unumber</pre><pre>    }<br>    <br>}</pre><p>⚡️In Kotlin, during class instantiation, the primary constructor is executed first, followed by the initializer block (init), and then the secondary constructor.</p><p>When a function is triggered, it takes up memory space, and similarly, a variable or a class instantiated with the “new” keyword starts occupying memory space from the moment it is created.</p><p><strong>Primary Constructor:</strong></p><ul><li>the “constructor” keyword is optional when defining a primary constructor for a class.</li><li>you can only define one primary constructor per class. If you don’t define a constructor, default constructor is primary constructor</li><li>Using var or val keywords with primary constructor variables implies that this structure is a global variable and you can manipulate it as you wish.</li></ul><p><strong>Secondary Constructor:</strong></p><ul><li>The “constructor” keyword is used to define a constructor in the body of a class.</li><li>it is possible to define multiple secondary constructors in a class.</li><li>A val or var keyword cannot be used inside a secondary constructor.</li></ul><pre>class Employee {<br> <br>      constructor (_id : Int, _name: String ) {<br>          var id: Int = _id<br>          var name: String = _name<br>          println(&quot;Employee id is: $id, &quot;)<br>          println(&quot;Employee name: $name&quot;)<br>      <br>      }<br> <br>       constructor (_id : Int, _name: String, _salary : Double) {<br>           var id: Int = _id<br>           var name: String = _name<br>           var salary : Double = _salary<br>           print(&quot;Employee id is: $id, &quot;)<br>           print(&quot;Employee name: $name, &quot;)<br>           println(&quot;Employee name: $salary&quot;)<br>       }<br>}</pre><p>❓If I can handle my tasks with the secondary constructor, why would I need a primary constructor?</p><ul><li>Primary constructor is required in situations like inheritance.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F23592893&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fag-gif-23592893&amp;image=https%3A%2F%2Fmedia.tenor.com%2FwQ5IlwEZqroAAAAC%2Fag.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f98b2283559fb86451bbde7ca34bbb0/href">https://medium.com/media/4f98b2283559fb86451bbde7ca34bbb0/href</a></iframe><p><strong>Source: </strong>It contains the lecture notes of the bootcamp.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c61a6b9f0b6d" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/primary-secondary-constructors-c61a6b9f0b6d">Primary &amp; Secondary Constructors</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Class]]></title>
            <link>https://towardsdev.com/class-c8e24c67fbf?source=rss-a95f6db0afc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8e24c67fbf</guid>
            <category><![CDATA[class]]></category>
            <category><![CDATA[data-class]]></category>
            <dc:creator><![CDATA[Sümeyra Özuğur-En]]></dc:creator>
            <pubDate>Wed, 17 May 2023 06:06:37 GMT</pubDate>
            <atom:updated>2023-05-17T11:14:06.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M54bq0udWFzTz3CMwSkyzw.png" /></figure><p><strong>Class</strong> is a template that contains properties and functions.</p><p><strong>Object:</strong> An instance of a class created to use the structures of that class.</p><blockquote>Class names begin with a capital letter.</blockquote><pre>class Car(){<br>    var speed = 0</pre><pre>    companion object{<br>        var wheel = 4<br>    }</pre><pre>    init{<br>        println(&quot;init call&quot;)<br>    }</pre><pre>    fun increaseSpeed(speed:Int):Int{<br>        this.speed += speed<br>        return this.speed<br>    }</pre><pre>    fun decreaseSpeed(speed:Int):Int{<br>        this.speed -= speed<br>        return this.speed<br>    }<br>}</pre><pre>fun main(){<br>   val car =Car() //initialize<br>   car.increaseSpeed(20)<br>   car.decreaseSpeed(8)<br>   println(car.speed) // 12 </pre><pre>}</pre><p>You can create objects and call these structures in other classes with these properties and functions in classes.</p><blockquote>When a class is initialized, its variables are created. They take up memory in the computer’s memory.</blockquote><p>Unused objects and variables are cleaned up with the help of the garbage collector. If an object or variable is used but will not be used later, it will still be cleaned up. However, it is important to note that we should not produce too many of these structures just because the garbage collector will clean them up. Otherwise, an “out of memory” exception may occur.</p><blockquote><strong>Statics</strong> are not structures that can be transferred to the garbage collector. They must live continuously so that we can access them whenever we want. Until the process death occurs, the garbage collector cannot touch the statics.</blockquote><h3>Data Class</h3><pre>data class CategoryModel (val id:Int, val name: String )</pre><ul><li>In a data class, the parameters in the primary constructor should either be defined with the var keyword or the val keyword. Using val is more appropriate here.✌🏼.</li><li>Data classes cannot be abstract, open, sealed, or inner.</li><li>Data classes have less capability than regular classes.</li><li>Data classes are used to hold data.</li><li>We create model structures using data classes.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F26299592&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fbye-gif-gif-26299592&amp;image=https%3A%2F%2Fmedia.tenor.com%2FhYHb-jHx0-4AAAAC%2Fbye-gif.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/61055b0d8342c52719676fe7a515aa95/href">https://medium.com/media/61055b0d8342c52719676fe7a515aa95/href</a></iframe><p><strong>Source: </strong>It contains the lecture notes of the bootcamp.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8e24c67fbf" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/class-c8e24c67fbf">Class</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Exception Handling]]></title>
            <link>https://towardsdev.com/kotlin-exception-handling-fffd379f5edf?source=rss-a95f6db0afc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fffd379f5edf</guid>
            <category><![CDATA[excepti]]></category>
            <category><![CDATA[try-catch]]></category>
            <dc:creator><![CDATA[Sümeyra Özuğur-En]]></dc:creator>
            <pubDate>Mon, 15 May 2023 07:45:01 GMT</pubDate>
            <atom:updated>2023-05-15T11:55:16.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_y_uhkD9PAg8W-tj2yScg.png" /></figure><p>We use try-catch blocks in codes that have a high possibility of error. In cases where we receive data from users, databases, or external services, the probability of error is very high. Try-catch blocks are used in such situations.</p><p>Let’s go through an example. Let’s say we are getting numbers from the user and performing a division operation with those numbers. Whenever there is a user involved, we should always consider the possibility of an error 😅. We put this code into a try block and write the code we want to run in the catch block if an error occurs.</p><pre>try{<br>    val numOne = 100<br>    val numTwo = 0<br>    val end = numOne/ numTwo<br>    prinln(end)<br>}catch(e:Exception){<br>    println(&quot;Lütfen sayısal 0 olmayan bir değer giriniz&quot;)<br>}finally{<br>  //Her durumda çalışmasını istediğimiz kod<br>}</pre><blockquote>The try-catch construct works together.</blockquote><pre>try{<br>// This is where the code that might cause errors is written<br>}catch{<br>//if an error occurs in the try block, this block is working<br>}</pre><p>What is the purpose of the “finally” keyword?</p><p>The “finally” block is used for operations such as safely closing resources (file, database connection, network connection, etc.).</p><p>Now to summarize:</p><blockquote><strong>try</strong>: Used in code blocks where errors may occur. Runs in any case.</blockquote><blockquote>c<strong>atch</strong>: Runs when an error occurs.</blockquote><blockquote><strong>finally</strong>: Contains code blocks that will run in any case.</blockquote><p>why we need the finally block since the code after it will be executed in any case.</p><ul><li>To prevent the code from running asynchronously and to make it run synchronously, it should be written under the finally block.</li></ul><p><strong>Source: </strong>It contains the lecture notes of the bootcamp.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F25055952&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Frachel-friends-gif-25055952&amp;image=https%3A%2F%2Fmedia.tenor.com%2FClQUyrcq3xsAAAAC%2Frachel-friends.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e69ca7e44c4f1522bb0558f714a7132/href">https://medium.com/media/7e69ca7e44c4f1522bb0558f714a7132/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fffd379f5edf" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/kotlin-exception-handling-fffd379f5edf">Kotlin Exception Handling</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Collections]]></title>
            <link>https://towardsdev.com/kotlin-collections-d397a0b1b4af?source=rss-a95f6db0afc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d397a0b1b4af</guid>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[set]]></category>
            <category><![CDATA[maps]]></category>
            <dc:creator><![CDATA[Sümeyra Özuğur-En]]></dc:creator>
            <pubDate>Sat, 13 May 2023 13:34:47 GMT</pubDate>
            <atom:updated>2023-05-15T17:23:07.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkCJasjzO56rX0S51liuRQ.png" /></figure><p>Collections are structures used to store and manipulate groups of data. These structures can be divided into three main types: List, Set, and Map.</p><p><strong>👉🏻List</strong></p><ul><li>We can access the elements by their index.</li><li>An element can occur more than once in a list</li></ul><p><strong>👉🏻Map</strong></p><ul><li>They consist of structures in the form of key-value pairs.</li><li>❗️The fastest data insertion into list elements is Map. It’s pretty good in terms of performance. Because he doesn’t have to calculate what the key is, we decide..</li></ul><blockquote><strong>Not:</strong> The json structure also works in the form of keys and values. It can be said that it is a map structure in terms of software language.</blockquote><p><strong>👉🏻Set</strong></p><ul><li>Each element in a Set occurs only once. Whenever you add an element to a Set, the structure checks if there is another one like it in the background. That’s why this structure is a bit more costly. Lists are preferred more often.</li><li>Case sensitivity is important.</li></ul><p>Kotlin offers two different types for these:</p><h4>1)Immutable Collection(read only)</h4><p>1. Immutable List –&gt; listOf<br>2. Immutable Map –&gt; mapOf<br>3. Immutable Set –&gt; setOf</p><h4>2)Mutable Collections(read and write)</h4><p>1. Mutable List –&gt; ArrayList, arrayListOf, mutableListOf<br>2. Mutable Map –&gt; HashMap, hashMapOf, mutableMapOf<br>3. Mutable Set –&gt; mutableSetOf, hashSetOf</p><h4>Kullanım Örnekleri:</h4><p>1)Immutable List:</p><pre>val listOF = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;)</pre><p>2) Mutable List:</p><pre>val arrayList = ArrayList&lt;String&gt;()<br>val arrayListOf = arrayListOf(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;)<br>val mutableListOf = mutableListOf(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;)</pre><p>3)Immutable Map:</p><pre>val mapOF = mapOf(1 to &quot;apple&quot;, 2 to &quot;banana&quot;, 3 to &quot;orange&quot;)</pre><p>4) Mutable Map:</p><pre>val hashMap = HashMap&lt;Int, String&gt;()<br>val hashMapOf = hashMapOf(1 to &quot;apple&quot;, 2 to &quot;banana&quot;, 3 to &quot;orange&quot;)<br>val mutableMapOf = mutableMapOf(1 to &quot;apple&quot;, 2 to &quot;banana&quot;, 3 to &quot;orange&quot;)</pre><p>5)Immutable Set:</p><pre>val setOF = setOf(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;)</pre><p>6) Mutable Set:</p><pre>val mutableSetOf = mutableSetOf(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;)<br>val hashSetOf = hashSetOf(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;)</pre><p>➡️ Generally, immutable collections are cheaper in terms of memory usage. This is because the amount of memory that will be occupied is known at the beginning, and then you cannot add or remove elements.</p><p>➡️ Collections can contain elements of different data types, in which case the type of the collection becomes comparable. However, this is not highly recommended.</p><p><strong>Source: </strong>It contains the lecture notes of the bootcamp.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F24669775&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Faom-sushar-aom-sushar-pray-wish-gif-24669775&amp;image=https%3A%2F%2Fmedia.tenor.com%2FPuwj1ixystwAAAAd%2Faom-sushar-aom.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c06b7e3e7efcc514dd4739c6487c634/href">https://medium.com/media/1c06b7e3e7efcc514dd4739c6487c634/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d397a0b1b4af" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/kotlin-collections-d397a0b1b4af">Kotlin Collections</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOP]]></title>
            <link>https://towardsdev.com/oop-adc37a20bbfd?source=rss-a95f6db0afc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc37a20bbfd</guid>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[abstr]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[interfaces]]></category>
            <dc:creator><![CDATA[Sümeyra Özuğur-En]]></dc:creator>
            <pubDate>Mon, 01 May 2023 11:48:57 GMT</pubDate>
            <atom:updated>2023-05-01T16:19:04.770Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpMLav7Kl_JEVlUepntRcQ.png" /></figure><p>If a programming language provides the features of encapsulation, inheritance, abstraction, and polymorphism, we say that the language follows the principles of OOP. Many modern programming languages such as Kotlin, Python, Swift, and Java support OOP principles.</p><p>We can think of coding as the process of translating everything we see in real life into code. During the coding process, our requirements may change, and we may need to add new things to our code. In such situations, we need to make changes to the code in the least possible places. This is known as code maintainability.</p><p>It is a programming principle that enhances code readability and enables us to write less code.</p><h4>➡️Encapsulation</h4><p>Encapsulating a class’s variables by keeping them private and making their functions public is a common practice. While it may seem unnecessary at first, it can be a lifesaver in practice. Allowing unrestricted access to a class’s variables can be unsafe. Accessing them through functions, on the other hand, provides us with the ability to restrict the variable’s properties as we see fit.</p><pre>class BankAccount {<br>    private var result: Double = 0.0 // private olarak erişilebilen bir veri üyesi</pre><pre>    fun saveMoney(amount: Double) {<br>        // hesaba para yatırma işlemi<br>        result += amount<br>    }</pre><pre>    fun spentMoney(amount: Double) {<br>        // hesaptan para çekme işlemi<br>        if (amount &lt;= result)  result -= amount<br>        else println(&quot;Üzgünüm yeterli bakiyeniz yok..&quot;)<br></pre><pre>    }</pre><pre>    fun getResult(): Double {<br>        // hesap bakiyesini alma işlemi<br>        return result<br>    }<br>}</pre><pre>fun main(){<br>    val bank = BankAccount()<br>    bank.saveMoney(20.0)<br>    bank.spentMoney(30.0)<br>    println(bank.getResult())<br>}</pre><p>Let’s talk a bit about visibility modifiers here.</p><p>In Kotlin, if you do not define any visibility modifier, the default value is “public”.</p><ul><li>“<strong>public”</strong> means that you can access the element from anywhere.</li><li>“<strong>private</strong>” means that you cannot access the element from outside of the class.</li><li>“<strong>protected</strong>” means that the element is protected, allowing access only through inheritance. This means that it can only be used in the classes that inherit from it.</li><li>“<strong>internal</strong>” means that you can access the element from anywhere within the same module. It cannot be accessed from outside of the module.</li></ul><h4>➡️İnheritance</h4><p>Inheritance allows one class to inherit the properties and behaviors of another class.</p><pre>open class Button(val label: String) {<br>    open fun printDescription() {<br>        println(label)<br>    }<br>}</pre><pre>class ImageButton(label: String, val image: String): Button(label) {<br>    override fun printDescription() {<br>        println(&quot;$label with image $image&quot;)<br>    }<br>}</pre><p>❓Instead of using inheritance, you can create an object from that class and access the method. Yes, that’s true, but sometimes you may want to evolve that method, and that’s where inheritance becomes useful.</p><p>✨In Kotlin, all classes are final by default, which means they cannot be inherited. Therefore, to make a class inheritable, you need to use the “open” keyword.</p><p>✨The methods inherited from the base class are used in the subclass with the “override” prefix. Also, not every function in the base class needs to be used in the subclass. It depends entirely on the needs and requirements of the subclass.</p><p>✨ When you inherit from a class that has a constructor, it becomes the primary constructor, and therefore, you cannot provide a secondary constructor. The primary constructor is necessary in such cases to fulfill the requirements of the inheritance.</p><p>✨ As child classes know and can do more than their parent classes, they may require more memory, indicating that child classes use more memory than their parent classes. Therefore, parent classes can be more performant. However, the performance impact of this memory usage may not always be significant, and it ultimately depends on the specific use case and implementation. In some cases, the added capabilities of child classes may be essential and outweigh any potential performance trade-offs.</p><p>✨ When inheriting, we need to provide parameters that match one of the constructors.</p><blockquote>In Kotlin, all classes are implicitly inherited from the “Any” class, which is the root of the class hierarchy.</blockquote><blockquote>The fact that Kotlin classes inherit from the “Any” class includes the common features of classes. For example, all classes have some methods such as “equals()”, “hashCode()”, and “toString()”.</blockquote><p>It is important to remember that inheritance is a feature that needs to be used carefully. Overuse of inheritance can lead to complex class hierarchies and tight dependencies, which can increase code complexity. Therefore, using inheritance only when it makes sense and is necessary is important in creating well-designed class hierarchies.</p><p>Let’s discuss something before moving on to the topic of abstract classes. Why did we declare the “button” instance as type Button instead of ImageButton, even though we won’t be accessing its functions?</p><p>This is called polymorphism (I will explain it in more detail later). In short, holding a reference like this is useful for us. Additionally, if we were to remove the overridden function under ImageButton, the code would then execute the method under the base class. It’s a super feature.🔥.</p><pre>fun main() {<br>    val button:Button = ImageButton(&quot;write&quot;,&quot;something&quot;)<br>    button.printDescription()//write with image something<br>                             //write<br>}</pre><h4>➡️Abstract</h4><p>✨They include methods with or without bodies</p><p>✨Abstract classes are not required to include abstract methods. However, a class that includes abstract methods must be an abstract class.</p><p>✨ We cannot create an object from an abstract class</p><p>✨ Abstract classes are commonly used as a base class</p><p>✨ It can contain a constructor</p><p>✨ It can include methods with or without bodies. The ‘abstract’ keyword is not used in methods with bodies. Those that use the ‘abstract’ keyword must be implemented in its sub class.</p><p>✨ Being a class, it provides inheritance only once”</p><p>✨ It has the ‘is-a’ property. (For example, ‘A officer is a staff member’)”</p><pre>abstract class GeometricShape {<br>    abstract fun calculateArea(): Double<br>    abstract fun calculateEnvironment(): Double<br>}</pre><pre>class Rectangle(private val length: Double, private val width: Double) : GeometricShape() {</pre><pre>    override fun calculateArea(): Double {<br>        return length * width<br>    }</pre><pre>    override fun calculateEnvironment(): Double {<br>        return 2 * (length + width)<br>    }<br>}</pre><pre>class Circle(private val yariCap: Double) : GeometricShape() {<br>    override fun calculateArea(): Double {<br>        return Math.PI * yariCap * yariCap<br>    }</pre><pre>    override fun calculateEnvironment(): Double {<br>        return 2 * Math.PI * yariCap<br>    }<br>}</pre><pre>fun main() {<br>    val dikdortgen:GeometricShape = Rectangle(5.0, 10.0)</pre><pre>    println(&quot; ${dikdortgen.calculateArea()}&quot;)<br>    println(&quot; ${dikdortgen.calculateEnvironment()}&quot;)</pre><pre>}</pre><h4>➡️İnterface:</h4><p>Adding the letter ‘I’ at the beginning of the name to indicate that the structure we define is an interface and adding ‘Impl’ to the end of the implementing class name is a best-practice example.</p><pre>interface IProduct {</pre><pre>    fun productList( ) : List&lt;String&gt;<br>    fun productAdd(data: String )</pre><pre>}</pre><pre>class WomanProductImpl : IProduct {<br></pre><pre>    override fun productList(): List&lt;String&gt; {<br>        return  arrayListOf(&quot;canta&quot;,&quot;elbise&quot;)<br>    }</pre><pre>    override fun productAdd(data: String){<br>      println(&quot;$data eklendi&quot;)<br>    }<br>}</pre><p>✨ Interfaces do not create a cost for us.</p><p>✨ Interfaces allow us to execute the program according to a certain order.</p><p>✨ Overriding functions within the interface is mandatory in the classes that inherit them.</p><p>✨ Interfaces do not contain constructors, as they are not classes.</p><p>✨ While classes can only inherit from a single class, interfaces enable us to support multiple inheritance.</p><p>✨ Objects cannot be created from interfaces.</p><p>✨ It can include methods with or without bodies. When inherited, it is mandatory to override the methods without a body.</p><p>✨ It works according to the can-do relationship (can add a product, can list products, etc.)</p><p>✨ Everything inside an interface must be public.</p><p>❓When we see the code block above, we might wonder why we’re creating interfaces instead of simply writing the code directly within the class and being done with it. While it may seem logical at first, this approach can cause headaches later on. For example, let’s say your company decides that they no longer want to sell women’s clothing and instead want to transition to men’s clothing.</p><pre>class ManProductImpl:IProduct{<br></pre><pre>    override fun productList(): List&lt;String&gt; {<br>        return  arrayListOf(&quot;ayakkabı&quot;,&quot;ceket&quot;)<br>    }</pre><pre>    override fun productAdd(data: String) {<br>        println(&quot;$data eklendi&quot;)<br>    }</pre><pre>}</pre><pre>fun main(){<br>    val woman:IProduct = WomanProductImpl()// bu satırı kaldırıp<br>    val man:IProduct = ManProductImpl()// bunu ekleyelim<br>    man.productAdd(&quot;Kemer&quot;)<br>}</pre><p>As you can see, instead of deleting and rewriting the code, we were able to handle our work with minimal changes.</p><h4>➡️Polymorphism</h4><p>The Turkish translation is polymorphism. A referance can be defined as it works differently when it references the subclasses below. Thanks to polymorphism, we add flexibility to our code. We make it more secure by reducing the direct connection.</p><p>Two types of polymorphism exist:</p><ul><li><strong>Compile Time(Overloading)</strong></li><li>Run Time(Overriding)</li></ul><h4>👉🏻Overloading(Compile Time)</h4><p>You cannot write two functions with the same name, but you can write them by changing the number or type of parameters. This is called <strong>overloading</strong>.</p><pre>fun sum(param1: Int) {<br>    // write something<br>}</pre><pre>fun sum(param1: String) {<br>    // ...<br>}<br>fun sum(param1:Int, param2:Int){<br>   // ...</pre><pre>}</pre><h4>👉🏻Overriding(Run Time)</h4><p>This can be defined as filling the code block by overriding it, as we have seen in the code examples above.</p><pre>class MainActivity : AppCompatActivity() {<br>    private lateinit var binding: ActivityMainBinding<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>    }<br>}</pre><p>The important thing to note here is that Base references and shows the properties of the subclass from which it was created.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F19177651&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fthank-you-alice-in-wonderland-thanks-gif-19177651&amp;image=https%3A%2F%2Fmedia.tenor.com%2FMg5vA3MVUA8AAAAC%2Fthank-you-alice-in-wonderland.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/78f3ffcd61f68dc15d00b1b48e9d08d2/href">https://medium.com/media/78f3ffcd61f68dc15d00b1b48e9d08d2/href</a></iframe><p><strong>Sources</strong></p><p><a href="https://www.youtube.com/c/KeKod">https://www.youtube.com/c/KeKod</a></p><p><a href="https://www.w3schools.com/kotlin/kotlin_oop.php">https://www.w3schools.com/kotlin/kotlin_oop.php</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc37a20bbfd" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/oop-adc37a20bbfd">🐋OOP</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object & Companion Object]]></title>
            <link>https://towardsdev.com/object-companion-object-ab9f2623639f?source=rss-a95f6db0afc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab9f2623639f</guid>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[companion-object]]></category>
            <category><![CDATA[statik]]></category>
            <dc:creator><![CDATA[Sümeyra Özuğur-En]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 01:36:29 GMT</pubDate>
            <atom:updated>2023-04-25T10:25:21.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TwUc8GJz1FB_0q4Lm1nq0A.png" /></figure><h4>Object:</h4><ul><li>Object declarations are defined as “object declaration” in Kotlin. Object declarations are thread-safe and initialized lazily.</li></ul><p><strong>thread-safe: </strong>If a component or code snippet is “thread safe”, it can produce correct results without causing incorrect results or erroneous behavior when called by multiple threads simultaneously. Here, the creation of the object is thread safe, but the methods inside it may not be thread safe.</p><p><strong>lazy-initialize: </strong>They are initialized when first called in the code</p><ul><li>The implementation of Singleton pattern in Kotlin is by using an object declaration, which creates a thread-safe and lazily initialized singleton instance.</li><li>It can be accessed by its own name.</li></ul><p>The foundation of Object-Oriented Programming (OOP) is based on a static structure, but you can think of it as a more specialized form.</p><pre>object{<br>    val pi = 3.14<br>}</pre><pre>class Value{<br>    companion object{<br>       val pi = 3.14<br>   }<br>}</pre><h4>Companion Object:</h4><ul><li>it occupies memory even if it is not called.</li><li>Each class can have only one companion object.</li><li>The concept is associated with the static keyword in Java.</li><li>It can be accessed using the class name.</li><li>It is preferred when a property is needed at the class level rather than a specific object.</li></ul><p>Additionally, statics have lifetimes that match the entire runtime of the program. This means that even after using your class, all these static variables cannot be touched by the Garbage Collector. Again, this means that we should use this part carefully in terms of memory.</p><p>Let’s give a small example where we can use static, and then let’s let you choose which of them you prefer😃.</p><p><strong>Example: </strong>Let’s say you are constantly switching from one page to another and coming back. Here, when you switch to another page, the structures on the back page are deleted by the garbage collector. When you come back, they are recreated. The same situation applies to the other page. There is a clear performance loss due to this constant zigzag situation. Here, using static can be a more efficient way. For instance, instead of creating objects every time, using a class-level property can be more efficient. For example, by using a class-level variable, you can temporarily store your data during page transitions and reuse this data when you come back. This avoids the constant creation and deletion of objects, resulting in improved performance.</p><p>🎃If I need this variable in different classes and cannot coordinate it with a shared view model, then I should definitely use static.</p><p><strong>Note:</strong> It is preferred to keep immutable data in static structures. If mutable data needs to be stored, it should be carefully considered. 😅</p><p><strong>Note2: </strong>It is recommended to use dependency injection instead of making classes Singleton. But why?</p><p>When a process death occurs, the static data is collected by the garbage collector. When the application is reopened, it cannot find the data held in the static fields (since the garbage collector has already collected them) and this can lead to memory leaks. If we had used dependency injection instead of Singleton design pattern, the necessary dependencies would be reconnected when the application is reopened, and the application would continue without any problems.</p><p>Dependency Injection provides a more flexible structure than the Singleton design pattern and can help reduce memory usage and improve testability.</p><p>That’s all for now. Take care and see you in another post…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F25170543&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fcant-thankyou-enough-gif-25170543&amp;image=https%3A%2F%2Fmedia.tenor.com%2FVPtj_CuypecAAAAC%2Fcant-thankyou-enough.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bf77cb81dee35817780decb86e67421/href">https://medium.com/media/0bf77cb81dee35817780decb86e67421/href</a></iframe><p><strong>Kaynak:</strong></p><p><a href="https://kotlinlang.org/docs/object-declarations.html#companion-objects">Object expressions and declarations | Kotlin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab9f2623639f" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/object-companion-object-ab9f2623639f">Object &amp; Companion Object</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coroutine]]></title>
            <link>https://towardsdev.com/coroutine-e358e8e0c990?source=rss-a95f6db0afc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e358e8e0c990</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Sümeyra Özuğur-En]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 10:15:28 GMT</pubDate>
            <atom:updated>2023-02-28T18:35:19.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zV9Z8m3eFc64vMafbMERQ.png" /></figure><p>To better understand this topic, let’s first touch on the concepts of function and thread.</p><p>➡️<strong>Function</strong>: We can define it as a chain of instructions that can receive input and as a result, the structure that gives us outputs.</p><p>➡️<strong>Thread</strong>:It determines the context in which the chain of instructions should be.</p><p>We usually do our work on the Main Thread. However we should use Main Thread for small operations.</p><p><strong>Example: </strong>UI interactions, button clicks, math operations, value assignment, logical operations…</p><p>What if we use the main thread for other processes (network, file download, image upload, database operations)?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FNx85vtTY70T3W%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FNx85vtTY70T3W%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExdHl5NHJ3bjI1OHJjYmFlczMyM2g5OXZqY3I2MHhnZnYxcjlsYW9xbyZlcD12MV9naWZzX2dpZklkJmN0PWc%2FNx85vtTY70T3W%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="313" frameborder="0" scrolling="no"><a href="https://medium.com/media/be0ba57969c703ef92876cac46613d18/href">https://medium.com/media/be0ba57969c703ef92876cac46613d18/href</a></iframe><p>The main thread is blocked and our app crashes.</p><p>We should use the multi-thread structure in order to perform the operations simultaneously. Thus, while one thread is working with one thing, another thread can work with another work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFNZHn89TA6B9t4URkunSQ.png" /></figure><p>We can also set it up so that this thread will run after finishing that thread.</p><p>⭐️⭐️But using threads is not a sensible approach as the number of threads increases, it can cause CPU exhaustion and memory issues that can result in crashes.</p><p>That’s where Coroutines come in. So, how does Coroutine handle this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10aWFOx6n0LR-Jiml1P_6w.png" /></figure><p>Only one Background Thread (Worker thread) is created, and Coroutine is built on top of it. This is precisely what Coroutine does.</p><p>👀 <strong>Features of Coroutine:</strong></p><ul><li><strong>Lightweight : </strong>Coroutines are much lighter than threads.</li><li>They work within a thread.</li><li>They can work in parallel like threads, wait for each other, and communicate with each other.</li><li><strong>Fewer Memory Leaks : </strong>When the scope in which the Coroutine is running is canceled, the Coroutine within that scope is also canceled.</li></ul><blockquote>Coroutines are NOT threads.</blockquote><p>Creating a coroutine is very cheap for systems. You can create and use thousands of Coroutines without encountering any memory problems.</p><blockquote>Coroutines require a Coroutine scope to start.</blockquote><h4>👻SCOPE</h4><ul><li>The word “Scope” means “extent” in English.</li><li>It is a structure that determines where and how Coroutine runs and its lifecycle.</li></ul><h4>1.Global Scope</h4><ul><li>If you want to run a Coroutine throughout the entire application, you should use the global scope.</li><li>By default, the <strong>coroutine context </strong>is defined, but if you want, you can set which thread you want to run it on. (I will explain the Coroutine context in detail in the Coroutine Scope section ✌🏼)</li><li>If we want to cancel the operations in this scope, we can use the cancel job.</li></ul><pre>val TAG = &quot;MainActivity&quot;<br>        Log.w(TAG,&quot;Main program starts: ${Thread.currentThread().name}&quot;)<br>        GlobalScope.launch {<br>            Log.w(TAG,&quot;Fake work starts: ${Thread.currentThread().name}&quot;)<br>            delay(1000)<br>            Log.w(TAG,&quot;Fake work finished ${Thread.currentThread().name}&quot;)<br>        }<br>        Log.w(TAG,&quot;Main program ends: ${Thread.currentThread().name}&quot;)<br><br>//Output:<br>//Main program starts: main<br>// Main program ends: main<br>// Fake work starts: DefaultDispatcher-worker-1<br>//Fake work finished DefaultDispatcher-worker-1</pre><p>🙊<strong>Code Comment:</strong> Global scope continues to work in the background without blocking the main thread.</p><blockquote><strong>Global scope </strong>should not be preferred as much as possible!!!</blockquote><pre>val job =GlobalScope.launch(Dispatchers.Default) {<br>       repeat(3){<br>           Log.w(TAG,&quot;Coroutine is working...&quot;)<br>           delay(1000)<br>            }<br>        }<br><br>  runBlocking {<br>       job.join()<br>       Log.w(TAG,&quot;Main Thread is working&quot;<br>   }<br><br>//Output<br>//Coroutine is working...<br>//Coroutine is working...<br>//Coroutine is working...<br>//Main Thread is working</pre><p>🙊<strong>Code Comment: </strong>We have used job.join() to make our operations in the GlobalScope run after they have finished.</p><blockquote><strong>launch </strong>is a function for starting a Coroutine. To use this function, we need to be within a Coroutine scope.</blockquote><blockquote><strong>Job: </strong>We can assign the things we run with launch to a job object. Later, we can either end the Coroutine’s lifecycle with the cancel method or set it to do something at the end.</blockquote><h4>2.ViewModel Scope</h4><ul><li>If you want to run a coroutine inside a ViewModel, you should use the ViewModel scope.</li><li>You do not need to manually cancel the operations in the scope. The ViewModel scope will automatically cancel when its life cycle ends.</li></ul><pre>fun doSomething() {<br>        viewModelScope.launch {<br>            // Asynchronous work<br>            delay(1000)<br>            Log.d(&quot;MyViewModel&quot;, &quot;Work done&quot;)<br>        }<br>    }</pre><h4>3.LifecycleScope</h4><ul><li>If you want to use a coroutine in an activity or fragment, you should use the Lifecycle scope.</li><li>You do not need to manually cancel the operations in the scope. The Activity or Fragment scope will automatically cancel when its life cycle ends.</li></ul><pre>class MyFragment: Fragment() {<br>   ...<br>   private fun doSomething(){<br>      lifecycleOwner.lifecycleScope.launch {<br>         // Asynchronous work<br>      }<br>   }<br>}</pre><h4>4.CoroutineScope</h4><p>If you want to use a coroutine outside of situations like ViewModel and Lifecycle, you should use the CoroutineScope.</p><pre>CoroutineScope(Dispatchers.Default).launch {<br>     // Asynchronous work<br>}</pre><p>It takes the <strong>coroutine context</strong>, which can be set using dispatchers, so you can specify which thread it should run on.</p><blockquote><strong>Coroutine context</strong>: It needs to know which data to work with.</blockquote><p><strong>➡Dispatchers.Default</strong></p><ul><li>Used in CPU-intensive tasks (image processing, filtering, sorting a long list alphabetically, etc.).</li></ul><p><strong>➡ Dispatchers.IO</strong></p><ul><li>Used in data processing, database read/write operations, networking (getting/writing data from the internet), file read/write operations, etc.</li></ul><p><strong>➡ Dispatchers.Main</strong></p><ul><li>Used for UI-related tasks.</li><li>Used when UI operations are needed inside a coroutine.</li></ul><p><strong>➡ Dispatchers.Unconfined</strong></p><ul><li>Different from other dispatchers. It does not change any threads. It adjusts itself based on the thread in which it is running.</li><li>Useful for unit testing.</li></ul><blockquote>You can change the dispatcher with “<strong>with context</strong>” or specify which dispatcher to use.</blockquote><pre>runBlocking {<br>    launch(Dispatchers.IO) {<br>     // Networking..<br>    withContext(Dispatchers.Main) {<br>        // Do something about Main Thread<br>            }<br>        }<br>    }</pre><h4>5.Run Blocking</h4><p>You should use it when you want to run something asynchronously. You don’t need a coroutine, but you want to call suspend functions.</p><ul><li>It stops the execution of subsequent code until the code inside it finishes running.</li><li>Usually used for test functions.</li></ul><pre>val TAG = &quot;MainActivity&quot;<br><br>Log.w(TAG,&quot;Main program starts: ${Thread.currentThread().name}&quot;)<br>runBlocking {<br>    launch {<br>        Log.w(TAG, &quot;Fake work starts: ${Thread.currentThread().name}&quot;)<br>            delay(1000)<br>            Log.w(TAG, &quot;Fake work finished ${Thread.currentThread().name}&quot;)<br>            }<br>}<br>Log.w(TAG,&quot;Main program ends: ${Thread.currentThread().name}&quot;)<br><br>//Output<br>//Main program starts: main<br>//Fake work starts: main<br>//Fake work finished main<br>//Main program ends: main</pre><p>🙊<strong>Code Comment</strong>: As you can see, there is no change in the thread and the code did not run asynchronously. In fact, even if we remove these scopes, it would still be the same. <strong>“delay(100)”</strong> needs to run inside a coroutine because it is a suspend function.✌🏼</p><h4>Suspend Fonksiyon</h4><ul><li>Functions that can run coroutines inside them.</li><li>!!! Suspend functions can call normal functions, but normal functions cannot call suspend functions.</li></ul><pre>val docRef = firebaseFirestore.collection(path).get().await()<br>        val favList = favDao.getFavTitles().orEmpty()<br>        val tempList = arrayListOf&lt;ProductModel&gt;()<br>        docRef.documents.forEach {  document -&gt;<br>            tempList.add(<br>                ProductModel(<br>                    document.id,<br>                    document.get(&quot;image&quot;) as String,<br>                    document.get(&quot;title&quot;) as String,<br>                    document.get(&quot;description&quot;) as String,// as? String ?: &quot;No description available&quot;,<br>                    document.get(&quot;price&quot;) as String,<br>                    document.get(&quot;quantiles&quot;) as String,<br>                    favList.contains(document.get(&quot;title&quot;) as String)<br>                )<br>            )<br>        }<br>        tempList<br>    }</pre><p>🙊<strong>Code comment</strong>: We used the suspend function for a long-running operation. With the <strong>“withContext”</strong>, we specified which dispatcher it will run on.</p><h4>Async ve Await</h4><ul><li>Async is used to write asynchronous code like launch</li><li>“Launch” returns a “Job” object, while “async” returns a “Deferred” object.</li></ul><pre>GlobalScope.launch(Dispatchers.IO){<br>            val num1 = async { networkCall1() }<br>            val num2 = async { networkCall2() }<br><br>            Log.d(TAG, &quot;Answer 1 is ${num1.await()}&quot;)<br>            Log.d(TAG, &quot;Answer 2 is ${num2.await()}&quot;)<br>        }<br><br>    }<br><br>    suspend fun networkCall2():String {<br>        delay(3000L)<br>        return &quot;Ozugur&quot;<br>    }<br><br>    suspend fun networkCall1():String {<br>        delay(3000L)<br>        return &quot;Sumeyra&quot;<br>    }</pre><p><strong>Code Comment:</strong> By using “async”, we enable the code to run asynchronously. We use “await” to obtain the result, which allows us to wait for the operations to finish in order to perform the assignment without blocking the thread.</p><blockquote>We can also accomplish this using “launch” and “join”, but using “async” and “await” is a more appropriate usage.⚡️</blockquote><p><strong>Note: </strong>To read this content in Turkish, <a href="https://ozugursumeyra.medium.com/coroutine-bb81715d193b">click </a>here.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F21514603&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fthank-you-bow-lisa-kudrow-friends-thanks-gif-21514603&amp;image=https%3A%2F%2Fmedia.tenor.com%2F49GR_5KPsNEAAAAC%2Fthank-you-bow.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/42f77bd2f6b0105ef36f21ee7de29b3c/href">https://medium.com/media/42f77bd2f6b0105ef36f21ee7de29b3c/href</a></iframe><p><strong>Sources</strong></p><p><a href="https://kotlinlang.org/docs/coroutines-guide.html">https://kotlinlang.org/docs/coroutines-guide.html</a></p><p><a href="https://www.youtube.com/watch?v=lmRzRKIsn1g&amp;t=4829s">https://www.youtube.com/watch?v=lmRzRKIsn1g&amp;t=4829s</a></p><p><a href="https://www.youtube.com/playlist?list=PLQkwcJG4YTCQcFEPuYGuv54nYai_lwil_">https://www.youtube.com/playlist?list=PLQkwcJG4YTCQcFEPuYGuv54nYai_lwil_</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e358e8e0c990" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/coroutine-e358e8e0c990">Coroutine😈</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scope Functions]]></title>
            <link>https://towardsdev.com/scope-functions-3faf64f2638f?source=rss-a95f6db0afc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3faf64f2638f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[function-scope]]></category>
            <category><![CDATA[function]]></category>
            <dc:creator><![CDATA[Sümeyra Özuğur-En]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 05:03:51 GMT</pubDate>
            <atom:updated>2023-03-01T13:20:04.866Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxE89aFW0RezCMypWhOHIA.png" /></figure><p>One of the reasons popular of kotlin is to handle a lot with less code. In fact, if you look at it, scope functions also serve this purpose.</p><h3>🌈 What are Scope Functions?</h3><ul><li>It prevents code duplication within the scope of the block of code and makes it simpler and more readable.</li><li>️Scope functions do not add any new technology features.</li></ul><p>We have 5 scope functions. These are with, let, run, apply, also.</p><p><strong>👉🏻let, run, also ve apply </strong>are extension function.</p><p><strong>👉🏻let, also</strong> -&gt; They reference to “it”and are renamed;</p><p><strong>👉🏻run, with, apply </strong>-&gt; They reference to “this” and are not renamed.</p><p>👀Scope Functions are quite similar to each other. <br>There are 2 different ways to separate them.<br>- The contex object they refer to (this or it)<br>- The value it returns</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*d-g00TaaHS_y-FofrOUg_Q.png" /></figure><h4>📌With Function</h4><ul><li>contex object -&gt; this</li><li>return value-&gt; lambda</li></ul><p>As you can see in the example below, we get mutableListOf(“one”, “two”, “three”) by saying with(numbers). In this scope, if we want, we can access the list itself or the properties of the list without typing numbers.</p><pre>val numbers = mutableListOf(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;)<br>    with(numbers) {<br>        println(&quot;&#39;with&#39; is called with argument $this&quot;)<br>        println(&quot;It contains $size elements&quot;)<br>    }<br></pre><pre>//Output<br>&#39;with&#39; is called with argument [one, two, three]<br>It contains 3 elements</pre><blockquote>The “with” function combined with a “binding” object is a common practice. Thus, you avoid the binding repetition to reach the view every time.</blockquote><h4>📌Let Function</h4><ul><li>contex object -&gt; it (can be named whatever you want)</li><li>return değeri -&gt; lambda</li></ul><p>Generally, it is used for null checking. That’s why you often see it like this ?.let{}. If the value is not null, this block will run. This protects us from Null Pointer Exceptions.</p><pre>private var number:Int ?= null</pre><pre>      val x = number?.let { writeSomething-&gt;<br>            val number2 = writeSomething+1<br>        }</pre><p>In this section, we see that x returns a value of Unit. If the last expression is an expression without assignment, then x’s value becomes its return value. In the code block below, x’s return value is of type integer.</p><pre>val x = number?.let {<br>    val number2 = it +1<br>    number2<br>}</pre><p>as previously mentioned, if the number is not null, this code block will run. If it is null, we check with “?:”.</p><p>⭐️So, we have said to run the code block if the number is not null and to return 3 if it is null.</p><pre>val x = number?.let {<br>      val number2 = it +1<br>      number2<br>  }?:3</pre><h4>📌Run Function</h4><ul><li>contex object -&gt; this</li><li>return value-&gt; lambda</li></ul><p>The “run” function is similar to the “let” function. Both can perform null checks and, if the last expression is an expression without assignment, x’s value becomes its return value.</p><p>So what is the difference between them?</p><ul><li>“run” takes “this” as a parameter, while “let” takes “it”.</li></ul><pre>val x = number?.run {<br>          val number2 = this +1<br>          number2<br>  }</pre><h4>📌Apply Function</h4><ul><li>contex object -&gt; this</li><li>return değeri -&gt; contex</li></ul><p>The “apply” function is used to make assignments to the members of the target object.</p><pre>class  Person{<br>    var age:Int =0<br>    var city:String =&quot;&quot;<br>}</pre><p>To create an object from such a class</p><pre>val adm =Person()<br>adm.age =32<br>adm.city = &quot;London&quot;</pre><p>You can use it with apply function.</p><pre>val person = Person().apply {<br>         age = 32<br>         city = &quot;London&quot;<br>        }</pre><h4>📌Also Function</h4><ul><li>contex object -&gt; it (you can name whatever you want)</li><li>value of return -&gt; contex</li></ul><p>It is similar to the<strong> apply function</strong>.</p><pre>val numbers = mutableListOf(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;)<br>        numbers.also {<br>                println(&quot;The list elements before adding new one: $it&quot;)<br>                it.add(&quot;6&quot;)}<br>println(numbers)<br>//Output<br>[one, two, three, 6]</pre><p><strong>Note: </strong>To read this content in Turkish, <a href="https://ozugursumeyra.medium.com/scope-functions-40a62a00cf46">click</a> here.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F16160957&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fthank-you-spongebob-thanks-muscles-ty-gif-16160957&amp;image=https%3A%2F%2Fmedia.tenor.com%2FlkRdc7JY8FUAAAAC%2Fthank-you-spongebob.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1600a9dee019611b345b7a858890c2a0/href">https://medium.com/media/1600a9dee019611b345b7a858890c2a0/href</a></iframe><p><strong>Source</strong></p><p><a href="https://kotlinlang.org/docs/scope-functions.html">Scope functions | Kotlin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3faf64f2638f" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/scope-functions-3faf64f2638f">Scope Functions</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[By Lazy]]></title>
            <link>https://medium.com/@ozugursumeyraenglish/by-lazy-b204a560ba64?source=rss-a95f6db0afc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b204a560ba64</guid>
            <dc:creator><![CDATA[Sümeyra Özuğur-En]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 17:52:56 GMT</pubDate>
            <atom:updated>2022-12-06T18:49:28.181Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRzFFQ-J81TJ7w5YMA7vOA.png" /></figure><p>The creation of objects is an expensive process for systems. Once an object is created, its properties are created in the constructor. Obviously, these occupy memory space. In general, when the more memory space is occupied, the longer it will take for the process to complete.</p><p>Well, what if the object is not created immediately upon creation, but only when it is called, and then even if the property we call is kept in memory, instead of re-creating in the places we call it, it returns the memory value?</p><p>Here is the by lazy function. Let’s go through a small example to understand better.</p><pre>val message by lazy{<br>    say(&quot;Hello&quot;)<br>    &quot;Hi&quot;<br>}<br><br>fun say(s: String) {<br>    println(s)<br>}<br><br>fun main(){<br>    println(message)<br>    println(message)<br>    println(message)<br>}</pre><pre>//Output<br>Hello<br>Hi<br>Hi<br>Hi</pre><p>So what exactly is going on here? Don’t be panic!!, I’m telling you right now.</p><p>There is a “message” variable in the block, which can be accessed by calling it. Values of output(”Hello” and “Hi”) ​​are thus displayed on the screen. This block does not work when the second and third “message” value is written. Because this worked before and our “message” value was assigned as “Hi”. From now on, only the value of this will appear in every running “message”. So, the block doesn’t work anymore we get the value in memory.</p><p>Lazy part is done. I hope everything is clear so far. Finally, let’s talk about the differences between lateinit and lazy.</p><h3>Lazy vs Lateinit</h3><p>✅ Lazy is used with the “val” keyword, while lateinit is used with the “var” keyword.</p><p>✅ While we can call functions inside a lazy function, lateinit cannot.</p><p>✅ While lateinit cannot be used with primitives, we can use lazy.</p><p>✅ While lateinit can not be used with nullable, lazy can.</p><p>✅ Lazy is initialised when it will be called the first time. Then it uses value in memory. After lateinit is initialized, it gets recreated wherever it is called</p><p>⭐As Bill Gates said, lazy is important . Take care and see you in the next article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMErZAMy1WhBlKlC-ghfIQ.png" /></figure><p><strong>Dipnot:</strong> To read this content in Turkish, <a href="https://ozugursumeyra.medium.com/by-lazy-ac735e495f8d">click</a> here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b204a560ba64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>