Sunday, 19 April 2020

Kotlin : Lambda Expressions (Post 13)

Hi ,

Continuing  , the series of Kotlin , here I am again discussing few things about Lambda Expressions.

The main aim of writing the Lambda Expressions is to simplify the  code and reduce the number of lines  , with easily understandable .

I am here sharing a simple example of Lambda Expression , and passing it in the argument of one functions . The  functions which are having lambda expressions as an argument , are called High Order Functions.


override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        /** Lambda Expressions
        variable name : Signature = {Parameters -> method body}
        */
        var myLambdaFunction: (Int, Int) -> Unit = { a, b -> println(a + b) }
        getSum(4, 5, myLambdaFunction)
    }

    /**
     * High Level Functions
     */
    fun getSum(a: Int, b: Int, myLambdaFunction: (Int, Int) -> Unit) {
        myLambdaFunction(a, b)
    }


Also we can call the above method like this as well :

   getSum(4, 5, myLambdaFunction)

   getSum(4, 5, { a, b -> println(a + b)})

   getSum(4, 5) { a, b -> println(a + b)}

This is very basic expression of Lambdas . For getting more uses of Lambdas we can check out here :

https://kotlinlang.org/docs/reference/lambdas.html


Kotlin : Interface (Post 12)

Hi ,

Here I am again sharing you one more concept in Kotlin programming language i.e. Interface.

In kotlin , the interfaces work slightly different . In jave we all know that we need to implement the Interface , then override the functions to execute that interface , but here in Kotlin , we can directly execute the interface and pass the argument within the function using "object" keyword , let's take a look :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        getSum(4,8, object : MyInterface{
            override fun execute(sum: Int) {
                println(sum)
            }
        })
    }
   fun getSum( a : Int , b : Int , listener : MyInterface ) {
      listener.execute(a+b)
   }
    interface  MyInterface {
        fun execute(sum : Int)
    }

Also one more thing , for interface in Kotlin , few methods can also contains the body also inside the interface , same as abstract class. What makes them different from abstract classes is that interfaces cannot store state :

  interface  MyInterface {
        fun execute(sum : Int)
        fun show (){
            println("Hi I am in interface")
        }
    }

In class level , interface will implement like this :

class Child : MyInterface {
    override fun execute(sum: Int) {
        // body
    }
}

So in this way we can implement the interfaces in Kotlin . In next post I will share one more interesting concept in Kotlin Language  , till then Happy Coding :) 

Friday, 17 April 2020

Kotlin : TailRec Functions (Post 11)

Hi ,

In this post I will share the information  about "TailRec Functions"

This function helps us to use recursion in more optimised way.

We all know , that recursion means , calling its own function from within the function, and this recursion if the function has been called 100 or 1000 times , then in Java or C programming  language , we may face the StackOverflowException .

But in Kotlin this recursion has been done with the help of TailRec Function, which prevents the "StackOverflowException" .

Let's have a look :

 tailrec private fun getPrint() {
        println("Hello All")
        getPrint()
    }

Like this , we can use the recursion function in a better way in Kotlin. 

Kotlin : Infix Functions (Part 10)

Hi ,

Here I am sharing another topic i.e. Infix Function


  • Infix functions can be a Member Function or Extension Function
  • These functions can have only single parameter
  • They have prefix of "infix"
  • All infix functions are extension function But all extension function are not Infix


Take a look :


 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var  i : Int  = 45
        var j : Int = 91
        var k = i findTheGreaterNum j //calling the infix function
        println("In I: $i & in J: $j , greater number is : "+ k)
    }
    
    /**
     * Extension Function
     */
    infix fun Int.findTheGreaterNum(j :Int) : Int {
        if(this > j)
            return this
        else
            return j
    }

So here , we can say that it improves the readability.

I will catch you later , till then Happy Coding :)






Kotlin : Extension Functions (Post 9)

Hi ,

Here is another post related to Kotlin basics for beginners , in this post I will discuss the Kotlin Extension Function ,let's get started :

So sometimes , we feel that one important functionality is missing from a class and
 we want to add that function :
we need to extend that class, and then add that function and then use that extended class.

But in Kotlin , helps definitely on this by providing Extension Functions

Extension Functions are:
  • - can "add" new functions to a class without declaring it 
  • - the new functions added behaves like "static" in java

So let's take a look in code first , then we will discuss briefly on this :


override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)
  var  i : Int  = 45
  var j : Int = 91
  println("In I: $i & in J: $j , greater number is : "+ i.findTheGreaterNum(j))
}

/**
 * Extension Function
*/
fun Int.findTheGreaterNum(j :Int) : Int {
        if(this > j)
            return this
        else
            return j
 }


Here we can see the there was no function "findTheGreaterNum()" in Int class , but we can make this like extension function of Int class .

Here this will annotate for i , bcoz  the function is class for i object.

Same like this we can make the extension functions for our own classes as well.

That's all for extension functions , will post more for kotlin , till then Happy Coding :) 

Wednesday, 7 August 2019

Kotlin : TextViews , EditText & Buttons(Post 8)

Hi ,

In previous post , I have started android development , with Kotlin programming language.
Now let's take a look how Textviews and Edittext will work .

I have created one layout , having 1 EditText , 1 TextView and 1 Button in it.

  • EditText will use , to get the input from the user. 
  • Input validation will check by clicking on Button . 
  • TextView is used to check the validation status of input and then change its text accordingly.


labels_layout.xml :


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Name"
android:ems="10"
android:id="@+id/editText"
android:layout_margin="20dp"
/>

<Button
android:text="Validate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_margin="20dp"/>

<TextView
android:text="Check Validation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:layout_margin="20dp"
android:background="@color/colorPrimary"
android:padding="10dp"
android:textColor="#FFFFFF"/>
</LinearLayout>



LabelActivity.kt

package com.kotlin_application 
import android.os.Bundle 
import android.support.v7.app.AppCompatActivity 
import android.widget.Button 
import android.widget.EditText 
import android.widget.TextView 
import android.widget.Toast 
import kotlinx.android.synthetic.main.labels_layout.* 

class LabelActivity : AppCompatActivity() { 

var isValid : Boolean = false 

override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.labels_layout) 
inItView()
} 

private fun inItView(){ 

val textView = findViewById<TextView>(R.id.textView2) 
val button = findViewById<Button>(R.id.button) 
val ediText = findViewById<EditText>(R.id.editText) editText.setText(R.string.app_name) 

button.setOnClickListener{ 
var inputValue : String = ediText.text.toString()

if (inputValue.isEmpty() || inputValue== null){

Toast.makeText(this, "Please enter something!", Toast.LENGTH_LONG).show() 
isValid = false

} 

else{

Toast.makeText(this, "You have entered: "+inputValue, Toast.LENGTH_LONG).show()
 isValid = true 

}

}

textView.setOnClickListener { 
var inputValue : String = ediText.text.toString()

if ((inputValue.isEmpty() || inputValue== null) && !isValid){

 Toast.makeText(this, "Not Validate", Toast.LENGTH_LONG).show()
textView.text = "Can not login , as input is not valid" 

} 

else{ 

Toast.makeText(this, "Validate String : "+inputValue, Toast.LENGTH_LONG).show() 

textView.text = "Login successful" 

} 
} 
} 
}
  • Here you can see , the click listeners are different , than java . 
  • To set Text on TextView , we need to just : textView.text = "Login successful"
  • To get the value from the EditText , we have to call it like this:
  •  var inputValue : String = ediText.text.toString()
  • Toast is same as java. 
Buttons:

There are below type , by which we can define the click listener for buttons :


button1.setOnClickListener()
{              
Toast.makeText(this,"button 1 clicked", Toast.LENGTH_SHORT).show()         
}  


Here are some screenshots: 
  
 

 

That's it for this post . Will continue with Intents in next post. 

Tuesday, 6 August 2019

Kotlin : Hello World Android App (Post 7)

Hi ,

After the basic of Kotlin App. Let's start android development with Kotlin language. In this post I am going to share the demo for simple hello world program with Kotlin language.

For setup of Kotlin Support , android studio will be required of 3.0 version and more.At the time of language selection , we need to select "kotlin" for programming language , when we create a new application.

When creating the android application with kotlin , we do not need to change the layouts , just src files will be changed.

Here I will just create one layout having textview in it ,and attach the activity with this textview . Let's have a look :

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools"
 xmlns:app="http://schemas.android.com/apk/res-auto"  
      android:layout_width="match_parent"  
      android:layout_height="match_parent" 
       tools:context=".MainActivity">

    <TextView    
      android:id="@+id/textView" 
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Hello World!"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>



MainActivity.kt:

package com.kotlindemo

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Run the code:


That's it for this post , in next post I will discuss how TextViews and EditText is used in Kotlin.




Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...