<?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: Prithviraj Kapil</title>
    <description>The latest articles on DEV Community by Prithviraj Kapil (@prithviraj_kapil).</description>
    <link>https://dev.to/prithviraj_kapil</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%2F3198390%2F3a4399c8-be2e-4eb7-b295-0af584ee498a.jpg</url>
      <title>DEV Community: Prithviraj Kapil</title>
      <link>https://dev.to/prithviraj_kapil</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/prithviraj_kapil"/>
    <language>en</language>
    <item>
      <title>Hello Folks. I have written my first post on dev to, about Scope Functions in Kotlin. Feel free to give it a read and drop a review or suggestion. Also, would love to know your favourite scope function, or your favourite feature of Kotlin. Happy reading!</title>
      <dc:creator>Prithviraj Kapil</dc:creator>
      <pubDate>Fri, 30 May 2025 09:10:39 +0000</pubDate>
      <link>https://dev.to/prithviraj_kapil/hello-folks-i-have-written-my-first-post-on-dev-to-about-scope-functions-in-kotlin-feel-free-to-4622</link>
      <guid>https://dev.to/prithviraj_kapil/hello-folks-i-have-written-my-first-post-on-dev-to-about-scope-functions-in-kotlin-feel-free-to-4622</guid>
      <description>&lt;div class="ltag__link--embedded"&gt;
  &lt;div class="crayons-story "&gt;
  &lt;a href="https://dev.to/prithviraj_kapil/classes-and-interfaces-in-kotlin-em3" class="crayons-story__hidden-navigation-link"&gt;Scope Functions in Kotlin&lt;/a&gt;


  &lt;div class="crayons-story__body crayons-story__body-full_post"&gt;
    &lt;div class="crayons-story__top"&gt;
      &lt;div class="crayons-story__meta"&gt;
        &lt;div class="crayons-story__author-pic"&gt;

          &lt;a href="/prithviraj_kapil" class="crayons-avatar  crayons-avatar--l  "&gt;
            &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3198390%2F3a4399c8-be2e-4eb7-b295-0af584ee498a.jpg" alt="prithviraj_kapil profile" class="crayons-avatar__image"&gt;
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;div&gt;
            &lt;a href="/prithviraj_kapil" class="crayons-story__secondary fw-medium m:hidden"&gt;
              Prithviraj Kapil
            &lt;/a&gt;
            &lt;div class="profile-preview-card relative mb-4 s:mb-0 fw-medium hidden m:inline-block"&gt;
              
                Prithviraj Kapil
                
              
              &lt;div id="story-author-preview-content-2543202" class="profile-preview-card__content crayons-dropdown branded-7 p-4 pt-0"&gt;
                &lt;div class="gap-4 grid"&gt;
                  &lt;div class="-mt-4"&gt;
                    &lt;a href="/prithviraj_kapil" class="flex"&gt;
                      &lt;span class="crayons-avatar crayons-avatar--xl mr-2 shrink-0"&gt;
                        &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3198390%2F3a4399c8-be2e-4eb7-b295-0af584ee498a.jpg" class="crayons-avatar__image" alt=""&gt;
                      &lt;/span&gt;
                      &lt;span class="crayons-link crayons-subtitle-2 mt-5"&gt;Prithviraj Kapil&lt;/span&gt;
                    &lt;/a&gt;
                  &lt;/div&gt;
                  &lt;div class="print-hidden"&gt;
                    
                      Follow
                    
                  &lt;/div&gt;
                  &lt;div class="author-preview-metadata-container"&gt;&lt;/div&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;

          &lt;/div&gt;
          &lt;a href="https://dev.to/prithviraj_kapil/classes-and-interfaces-in-kotlin-em3" class="crayons-story__tertiary fs-xs"&gt;&lt;time&gt;May 30 '25&lt;/time&gt;&lt;span class="time-ago-indicator-initial-placeholder"&gt;&lt;/span&gt;&lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;

    &lt;/div&gt;

    &lt;div class="crayons-story__indention"&gt;
      &lt;h2 class="crayons-story__title crayons-story__title-full_post"&gt;
        &lt;a href="https://dev.to/prithviraj_kapil/classes-and-interfaces-in-kotlin-em3" id="article-link-2543202"&gt;
          Scope Functions in Kotlin
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;div class="crayons-story__tags"&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/kotlin"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;kotlin&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/oop"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;oop&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/tutorial"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;tutorial&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/programming"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;programming&lt;/a&gt;
        &lt;/div&gt;
      &lt;div class="crayons-story__bottom"&gt;
        &lt;div class="crayons-story__details"&gt;
            &lt;a href="https://dev.to/prithviraj_kapil/classes-and-interfaces-in-kotlin-em3#comments" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left flex items-center"&gt;
              Comments


              &lt;span class="hidden s:inline"&gt;Add Comment&lt;/span&gt;
            &lt;/a&gt;
        &lt;/div&gt;
        &lt;div class="crayons-story__save"&gt;
          &lt;small class="crayons-story__tertiary fs-xs mr-2"&gt;
            4 min read
          &lt;/small&gt;
            
              &lt;span class="bm-initial"&gt;
                

              &lt;/span&gt;
              &lt;span class="bm-success"&gt;
                

              &lt;/span&gt;
            
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;/div&gt;


</description>
      <category>kotlin</category>
      <category>oop</category>
      <category>tutorial</category>
      <category>programming</category>
    </item>
    <item>
      <title>Scope Functions in Kotlin</title>
      <dc:creator>Prithviraj Kapil</dc:creator>
      <pubDate>Fri, 30 May 2025 06:30:00 +0000</pubDate>
      <link>https://dev.to/prithviraj_kapil/classes-and-interfaces-in-kotlin-em3</link>
      <guid>https://dev.to/prithviraj_kapil/classes-and-interfaces-in-kotlin-em3</guid>
      <description>&lt;p&gt;Hello folks, I have taken a deep dive in Kotlin lately, and I came across an intermediate level topic, “Scope functions”. Sounds scary right? It’s not, let’s find out!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is a scope?&lt;/strong&gt;&lt;br&gt;
Basically, a scope in any programming langauge is defined as the space in which a particular object, or a particular variable is recognized, or can be accessed. There are 2 scopes at large&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Global scope&lt;/strong&gt;: A variable or object that is recognized anywhere in the program.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Local scope&lt;/strong&gt;: A variable or object that is only recognized in a block or a function.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Scope functions in Kotlin are defined as functions, that create a local scope around the object, and provide a reference to the same object to make changes to it or execute some code.&lt;/p&gt;

&lt;p&gt;Each scope function in kotlin, takes in a lambda expression, and either returns the object or some result of the lambda expression at the end of execution. One can reference the object in the temporary local scope with keywords like it, or this.&lt;/p&gt;

&lt;p&gt;There are 5 different scope functions in Kotlin, let us understand each one in detail with an example.&lt;/p&gt;

&lt;p&gt;Scope functions in Kotlin are&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;let&lt;/li&gt;
&lt;li&gt;apply&lt;/li&gt;
&lt;li&gt;run&lt;/li&gt;
&lt;li&gt;also&lt;/li&gt;
&lt;li&gt;with&lt;/li&gt;
&lt;/ol&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Let&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let scope function is generally used to check null safety while assigning values to a variable, and then returning the object with further actions if required.&lt;/p&gt;

&lt;p&gt;Look at the code snippet below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun dialNumber(phoneNumber: String){
  println("Dialing number: ${phoneNumber}")
}

fun getPhoneNumber(): String{
  return "Some random phone number"
}

fun main(){
  val phoneNumber: String? = getPhoneNumber();

  dialNumber(phoneNumber);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, in the above code snippet&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;There are 3 function, &lt;em&gt;dialNumber( )&lt;/em&gt;, &lt;em&gt;getPhoneNumber( )&lt;/em&gt; and &lt;em&gt;main( )&lt;/em&gt; function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;dialNumber( )&lt;/em&gt; takes a String parameter and &lt;em&gt;getPhoneNumber( )&lt;/em&gt; returns a String value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the main( ) function, a nullable String variable &lt;em&gt;phoneNumber&lt;/em&gt; stores the number from &lt;em&gt;getPhoneNumber( )&lt;/em&gt; function, and is passed to &lt;em&gt;dialNumber( )&lt;/em&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Problem in the above code snippet is, that &lt;em&gt;dialNumber( )&lt;/em&gt; requires a String parameter, whereas we are passing a nullable String type phoneNumber to it.&lt;/p&gt;

&lt;p&gt;Now, look at the code snippet below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun dialNumber(phoneNumber: String){
  println("Dialing number: ${phoneNumber}")
}

fun getPhoneNumber(): String{
  return "Some random phone number"
}

fun main(){
  val phoneNumber: String? = getPhoneNumber();

  val didDial = phoneNumber?.let{
    dialNumber(it)
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What is happening here is&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We perform a safe call on &lt;em&gt;phoneNumber&lt;/em&gt; using ?, followed by let.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;let&lt;/strong&gt;, creates a temporary scope, takes a lambda function where &lt;em&gt;phoneNumber&lt;/em&gt; can be accessed using &lt;strong&gt;it&lt;/strong&gt; keyword.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;dialNumber&lt;/em&gt; is called in this scope with reference to &lt;em&gt;phoneNumber&lt;/em&gt;, using &lt;strong&gt;it&lt;/strong&gt; call.&lt;/li&gt;
&lt;li&gt;Result of the function is assigned to the &lt;em&gt;didDial&lt;/em&gt; variable.
Using let, a safe null check is performed.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Using &lt;strong&gt;let&lt;/strong&gt;, a safe null check is performed.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;2. Apply&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;apply is another scope function. Apply is mostly used to initialize data to fields of an object, or to run method functions of an object during the time of object creation.&lt;/p&gt;

&lt;p&gt;For example, without using apply&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Student(){
  val id: String?
  fun calculateGrade() = println("Calculating score!")
  fun markAttendance() = println("Marked attendance!")
}

fun main(){
  val student: Student = Student()

  student.id = "1"
  student.calculateGrade()
  student.markAttendance()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we first need to create an instance of the student class, in order to access or modify its variables and functions.&lt;/p&gt;

&lt;p&gt;For simpler classes, the approach feels simpler, but for complex classes with different and many properties, this process becomes cumbersome.&lt;/p&gt;

&lt;p&gt;Using &lt;strong&gt;apply&lt;/strong&gt;, we can access and modify properties of an object at the time of creation&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Student(){
  val id: String?
  fun calculateGrade() = println("Calculating score!")
  fun markAttendance() = println("Marked attendance!")
}

fun main(){
  val student: Student = Student().apply{
    id = "1"
    calculateGrade()
    markAttendance()
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;3. Run&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Run has a similar use case as apply, additionally one can use run to execute and compute some code while accessing properties of an object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Student(){
  val id: String?
  fun calculateGrade() = println("Calculating score!")
  fun markAttendance() = println("Marked attendance!")
}

fun main(){
  val student: Student = Student().apply{
    id = "1"
  }.run{
    calculateGrade()
    markAttendance()
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;4. Also&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Also can be used to perform extra computation with an object in the local scope and then return the object for continuation of flow of code. For example: Printing logs in the terminal&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Student(){
  val id: String?
  fun calculateGrade() = println("Calculating score!")
  fun markAttendance() = println("Marked attendance!")
}

fun main(){
  val student: Student = Student().apply{
    id = "1"
  }.run{
    calculateGrade()
    markAttendance()
  }.also{
    println("Student initialized with id: $id");
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;5. with&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;with is not an extension function, and thus the syntax is different than other scope functions. Here the object is passed as an argument to &lt;strong&gt;with&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Let’s understand with an example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Car{
  fun drive(speed: Int, acceleration: Double, distance: Double){
    println("Driving car at $speed with $acceleration till $distance");
  }

  fun getMileage(distance: Double, time: Double, fuelConsumed: Double){
    println("Calculating mileage for $distance, in $time, with $fuelConsumed");
  }
}

fun main(){
  val userDummyTestCar1: Car = Car()

  userDummyTestCar1.drive(10, 20, 15)
  userDummyTestCar1.getMileage(12, 11.4, 12.5)
  userDummyTestCar1.drive(21, 33.43, 18.1)
  userDummyTestCar1.getMileage(22.1, 11.42, 23.54)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, in the above code base, the same user object is called redundantly. The code can be simplified here using &lt;strong&gt;with&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val userDummyTestCar1: Car = Car()

with(userDummyTestCar1){
  drive(10, 20, 15)
  getMileage(12, 11.4, 12.5)
  drive(21, 33.43, 18.1)
  getMileage(22.1, 11.42, 23.54)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;br&gt;
Below is the overview of each scope function one can refer to.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1rbp4gt17a82w2jloju9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1rbp4gt17a82w2jloju9.png" alt="Image description" width="800" height="586"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Sources&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Official kotlin docs — &lt;a href="https://kotlinlang.org/docs/kotlin-tour-intermediate-scope-functions.html" rel="noopener noreferrer"&gt;https://kotlinlang.org/docs/kotlin-tour-intermediate-scope-functions.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hope this was a good read.&lt;/p&gt;

&lt;p&gt;See you again&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzowgue81ctnv3038ptd0.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzowgue81ctnv3038ptd0.jpg" alt="Image description" width="564" height="564"&gt;&lt;/a&gt;&lt;/p&gt;

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