<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Tuhin Chakraborty</title>
    <description>The latest articles on DEV Community by Tuhin Chakraborty (@tuhin).</description>
    <link>https://dev.to/tuhin</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F155691%2F6c63d490-d752-453b-afef-46bd7dc63ffb.png</url>
      <title>DEV Community: Tuhin Chakraborty</title>
      <link>https://dev.to/tuhin</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tuhin"/>
    <language>en</language>
    <item>
      <title>Kotlin Scope Functions</title>
      <dc:creator>Tuhin Chakraborty</dc:creator>
      <pubDate>Sun, 26 Apr 2020 09:23:13 +0000</pubDate>
      <link>https://dev.to/tuhin/kotlin-scope-functions-1nhk</link>
      <guid>https://dev.to/tuhin/kotlin-scope-functions-1nhk</guid>
      <description>&lt;h1&gt;
  
  
  Scope Functions
&lt;/h1&gt;

&lt;h2&gt;
  
  
  run, with, let, apply, also
&lt;/h2&gt;




&lt;h3&gt;
  
  
  First things first, They are &lt;strong&gt;&lt;em&gt;higher order functions&lt;/em&gt;&lt;/strong&gt;
&lt;/h3&gt;

&lt;h4&gt;
  
  
  But... What are higher order functions anyways
&lt;/h4&gt;

&lt;p&gt;On a very basic level they execute a function which is supplied to it. The Kotlin standard library is full of higher order functions. One of them being &lt;a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/repeat.html"&gt;repeat&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public inline fun repeat(times: Int, action: (Int) -&amp;gt; Unit)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The repeat function takes an action as an argument and returns Unit, but a higher order function can return any object. If you would want to invoke repeat, you would have to pass a function to this which will be invoked by the &lt;em&gt;repeat&lt;/em&gt; function.&lt;br&gt;
e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    repeat(3) {
        println("current value $it")
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;If you would want to write my very own higher order repeat function you can follow the same syntax.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    fun &amp;lt;T&amp;gt; T.myFunction(action: (T) -&amp;gt; String) {
        ...
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So, with that knowledge we can approach scope functions knowing they are higher order functions provided by the Kotlin standard library just like &lt;a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/repeat.html"&gt;repeat&lt;/a&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;run&lt;/strong&gt;
Takes an expression which is a piece of code, and executes it. This may or may not return a value. The whole idea of the run scope function is to &lt;em&gt;run&lt;/em&gt; a piece of code.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    data class Person(
        var name: String,
        var age: Int,
        var job: String
    ) {
        fun printPerson() = println(this)
    }

    val john = Person("John Doe", 20, "Plumber")
    val jane = Person("Jane Doe", 20, "Waitress")

    john.run {
        if (age &amp;gt; jane.age) println("John")
    }

    john.run {
        if (age &amp;gt; jane.age) this else jane
    }.printPerson()

    run {
        if (john.age &amp;gt; jane.age) john else jane
    }.printPerson()

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;with&lt;/strong&gt;
Exactly the same as &lt;em&gt;run&lt;/em&gt;, the only difference being it takes a receiver as an input. It is the same as calling run with an object instead of an argument.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    with(john) { // similar to the run function being called with the object
            age += 1
            "Age is $age"
        }.printThis()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;let&lt;/strong&gt;
&lt;em&gt;let&lt;/em&gt; takes a 'this' value and performs operations on &lt;em&gt;it&lt;/em&gt; (see what I did there..) and may or may not return a value.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    john?.let {
            it.age += 1
            "Age is ${it.age}"
        }.printThis() ?: defaultValue()

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;let&lt;/em&gt; is most useful when used with Kotlin's null checks. This allows you to execute a piece of code only when an object exists.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;apply&lt;/strong&gt;
It takes an object argument and returns the same object. It is very useful when we are transforming the object.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    jane.apply {
        jane.age = 22
        jane.job = "Restaurant Owner"
    }.printPerson()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Another use case of &lt;em&gt;apply&lt;/em&gt; is to initialize objects. In the below case the property name can be &lt;a href="https://kotlinlang.org/docs/reference/properties.html"&gt;lazily initialized&lt;/a&gt; or transformed using apply.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    val apply = Planet().apply {
        name = "Earth"
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;also&lt;/strong&gt;
Is similar to &lt;em&gt;apply&lt;/em&gt;, the only difference being &lt;em&gt;it&lt;/em&gt; receives a lambda which is accessed within the lambda with a name.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   val apply = Planet().also {
        it.name = "Earth"
    } 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



</description>
      <category>kotlin</category>
      <category>tutorial</category>
      <category>programming</category>
      <category>jvm</category>
    </item>
  </channel>
</rss>
