Skip to content

Instantly share code, notes, and snippets.

@Bhavdip
Last active October 9, 2017 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bhavdip/47c11c229579551b496badd610ca547c to your computer and use it in GitHub Desktop.
Save Bhavdip/47c11c229579551b496badd610ca547c to your computer and use it in GitHub Desktop.
kotlin_tips_part1.md

Which is a new programming language that is a pragmatic, safe,concise, and interoperable alternative to Java.With Kotlin, you can implement your projects with less code, a higher level of abstraction, and fewer annoyances

Kotlin is concise, safe, pragmatic, and focused on interoperability with Java code. It can be used almost everywhere Java is used today - for server-side development,Android apps, and much more. Kotlin works great with all existing Java libraries and frameworks and runs with the same level of performance as Java.

This allows for shorter code and greater flexibility in creating data structures.But the downside is that problems like misspelled names can’t be detected during compilation and lead to runtime errors.

The ability of the compiler to determine types from context is called type inference.

Performance - Calling methods is faster because there’s no need to figure out at runtime which method needs to be called.

Maintainability-Working with unfamiliar code is easier because you can see what kind of objects the code is working with.

The most important of those is Kotlin’s support for nullable types.Which lets you write more reliable programs by detecting possible null pointer exceptions at compile time.

Kotline is functional programming language.

First-class function: You work with functions as values. You can store them in variables,pass them as parameters, or return them from other function.

Immutability: You work with the immutbale objects, which guarantees that there state can't change after their creation.

No side effects: You use pure functions that return the same result given the same inputs and don't modify the state of other object or interact with outside world.

What benefits can you gain from writing the code in the function style?

1.Conciessness: Working with functions as value gives you much more power of abstraction, which lets you avoid duplication in your code. Imagine that you have two similar code fragment that implement similar task but different in details. You can easily extract the common part of logic into a function and pass the differing parts as parameters. Those parameters are themselves functions but you can express them using a concise syntax for functions called lambda expressions:

fun findAlice() = findPerson{ it.name= 'Alice' }

fun findBob() = findperson{ it.name='Bob'}

2.Safe Multithreading:One of biggest sources of errors in multithreaded programs is modification of same data from multiple threads without proper synchronization. If you use pure function and immutable data structure, you can sure that such unsafe modifications won't happen.

3.Easier Testing: Code without side effects is usually easer to test. Functions can be tested in isolation without requiring a lot of setup cpde

@Bhavdip
Copy link
Author

Bhavdip commented Oct 7, 2017

1.Kotlin Program runs on JVM
2.Kotlin and Android IDE is made by the same company name is JetBrains.
3.Kt or Java code always run on top of JVM.
4.You can call Java in Kotlin

/**
 * Created by bhavdip on 10/7/17.
 */
public class Customer1 {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private String name = "Hello";
}

fun main(argus: Array<String>){
    println("Hello")

    var name = Customer()

    name.name = "ABCD"

    println("Hello world: ${name.name}")

    var cust = Customer1()

    cust.name = "bhavdip" //this will call setter customer 1 method.

    println(cust.name) // this will call getter of customer 1 method

}

@Bhavdip
Copy link
Author

Bhavdip commented Oct 7, 2017

How to convert a Java class to Kotlin Class. It is easy in IntelliJ IDE You will get the option for code>Convert Java file to Kotline File.

Kotline file compiles into a class file which in java class file. If we decompile class file we can see the java code instead of Kotlin. It means you are writing a better java.

@Bhavdip
Copy link
Author

Bhavdip commented Oct 7, 2017

In Java, we have two variable instance and local to print the variable with text in kotlin use $sign.

    var num1 : Int = 4
    var num2 : Int = 3
    var result = num1 + num2
    println("The addition of $num1 and $num2 is $result")

You can use the brackets for fetch the value of object see the example below:


 class Customer{
   var name : String = ""
 }

  var bhavdip = Customer() //<- this is object in kotlin
  bhavdip.name = "Mr.Bhavdip" //access the properties of class customer
  println("A new customer ${bhavdip.name}") // print the value of that object

@Bhavdip
Copy link
Author

Bhavdip commented Oct 7, 2017

If Else Statement in Kotlin

Below the simple way to write a If else in Kotlin

fun main(argus: Array<String>){
    var num1 : Int = 4
    var num2 : Int = 3

    var result : Int

    if(num1 > num2) // check if num1 is grater than num2
        result = num1
    else
        result = num2
    
    println(result)
}

You can see that above code is the same as we did in java then what's the new thing in kotlin. Kotlin is not just only upto If else.

It is not a branching statement it is also an expression. What is an expression? an expression is something that is returned to a value. If you getting something back then it is an expression. Please see the example:

fun main(argus: Array<String>){
    var num1 : Int = 4
    var num2 : Int = 3
    
    var result = if(num1 > num2) // here we use expression.
         num1
    else
         num2

    println(result)
}

String comparison in kotlin

In Java if you know we use equals function for compare the two string.

fun main(argus: Array<String>){
    var password : String = "ABC"
    var tryPassword: String = "abc"

    if(password.equals(tryPassword)){
        println("same")
    }else{
        println("not same")
    }
}
result: not same.

But in kotlin use (==) for compare two string object.

fun main(argus: Array<String>){
    var password : String = "ABC"
    var tryPassword: String = "ABC"

    if(password == tryPassword){
        println("same")
    }else{
        println("not same")
    }
}
Result: Same

@Bhavdip
Copy link
Author

Bhavdip commented Oct 7, 2017

NULL Handling in Kotlin

By default you would not allow to assign the null value. If you could't able to assign the null value it prevent the null pointer exception on future. Kotlin by default does not allow to assign null value.

class Customer1 {

    var name = "Hello"
    
    var firstName: String = null; // Null can't be a value for non-null string type.
}

In case you force to use it then you can use (?) sign at end of type.

class Customer1 {

    var name = "Hello"

    var firstName: String? = null;
}
fun main(argus: Array<String>){
    var cust: Customer? = Customer() // force to use null customer 
    cust = null // we assign null
    println(cust?.name) // ? would allow us to use it otherwise at compile time it will show warning.

}

Thats how a kotlin is more stable compare to java. We handling the null pointer exception. If you want to assign a null value you have to put (?)

@Bhavdip
Copy link
Author

Bhavdip commented Oct 7, 2017

Switch Statement When Expression.

val is constant. In java final constant where in kotlin val is final immutable it would not change once creation.

In Kotlin we have when not switch. Everything in kotlin is expression.

fun main(argus: Array<String>){
    val num: Int = 2
    var result = when(num){
        1 -> "1"
        2 -> "2"
        3 -> "3"
        else -> "Give a proper input"
    }

    println("${result}")
}
Output: 2

In switch we can pass string, int. the best part is you can return something as expression and store result as value.

@Bhavdip
Copy link
Author

Bhavdip commented Oct 8, 2017

Range and Loops

fun main(args : Array<String>){
  var nums = 1..5
  for(index in nums){
    println("Index: ${index}")
  }
}
Output: 
Index: 1
Index: 2
Index: 3
Index: 4
Index: 5
//We can use step for jump the index 

  for(index in nums step 2){
    println("Index: ${index}")
  }
Index: 1
Index: 3
Index: 5
   //For reversed
    var nums = 1..16
    for(a in nums.reversed()){
        println(a)
    }

    //until

    var nums = 1 until  16

    for(index in nums){
        println(index)
    }

    //Charater rang
    var char = 'A'..'z'
    for(index in char){
        println(index)
    }
//for loop with key and value
      var nums = listOf(1,2,3,4,5,6)

     // this will return key and value
    for((k,v) in nums.withIndex()){
        println("Key:[$k] and Value[$v]" )
    }

How to use map in kotlin

     //Tree Map
    //must have to import  import java.util.*
    var customer = TreeMap<String,Int>() //Java Tree Map with kotlin.

    customer["A"] = 1
    customer["B"] = 2
    customer["C"] = 3

    for((name,value) in customer){
        println("Key[$name] and Value[$value]")
    }

@Bhavdip
Copy link
Author

Bhavdip commented Oct 8, 2017

Function Expression

//Function call and it return in kotlin

fun main(args: Array<String>){

    var result = addTwoNumber(10,100)

    println(result)
}

fun addTwoNumber(a: Int, b: Int) : Int{
    return a+b
}

The above example may only write in single line this is the beauty of kotlin.

fun main(args: Array<String>){

    var result = addTwoNumber(10,100)

    println(result)
}

/*fun addTwoNumber(a: Int, b: Int) : Int{
    return a+b
}*/

fun addTwoNumber(a: Int, b: Int):Int = a+b

fun maxNumberFinding(a : Int, b : Int) : Int{
    if(a >b)
        return a
    else
        return b
}

@Bhavdip
Copy link
Author

Bhavdip commented Oct 8, 2017

Function Calling from Java

We don't have static keyword in kotlin

Below is java class Runner.Java and which is calling method of Kotlin function. You have to create class and object for function calling but in kotlin we does not have class. To call kotlin fun in java class we need class name. So In kotlin file name is consider the class name and the function inside it static way to access it.

public class Runner {

    public static void main(String args[]){

        int result = KRunnerKt.maxNumberFinding(100,1100); // Notice: KRunnerKt here at end Kt is kotlin file
        System.out.println(result);
    }
}
//kRunner.kt
fun maxNumberFinding(a : Int, b : Int) : Int{
    if(a >b)
        return a
    else
        return b
}

As mentioned above in kotlin calling fun in java classs we need the class object. When we call Kotlin class it will add (Kt) at end of class name see in above example. To avoid that kind of keyword at end of class name you can use some annotation in your kotlin file. See below is the example. It must be added on top of the file above the package declaration.

KRunner.kt

@file:JvmName("Runners") // <--- This is the annotation

package FunctionCall


fun maxNumberFinding(a : Int, b : Int) : Int{
    if(a >b)
        return a
    else
        return b
}

//Runner.Java
public class Runner {

    public static void main(String args[]){

        int result = Runners.maxNumberFinding(100,1100);// Notice: here you can see that the we can overrider the file name
        System.out.println(result);
    }
}

That means if you does not use the annotation then by default it will consider a file name as class name.

@Bhavdip
Copy link
Author

Bhavdip commented Oct 8, 2017

Default Name and Parameters.

This is something new and that is not present in java.

fun main(args: Array<String>){
    var finalAmt = calAmount(1000);
    println(finalAmt)
}

fun calAmount(amount: Int) : Int{
    return (amount + amount * 0.4//<-- interest rate).toInt(); // kotlin to convert the double in Int.
}

OutPut: 1400

In the same example 0.40 is interest rate of amount. In case of to make it dynamic we can take it as parameter.

fun main(args: Array<String>){
    var finalAmt = calAmount(1000,0.40)

    println(finalAmt)
}

fun calAmount(amount: Int, interestRate : Double) : Int{
    return (amount + amount * interestRate).toInt();
}

Now a magic happen here you can see in below code the parameter has default value hook so incase we are not passing the value from calling place it will take as default value.

fun main(args: Array<String>){
    var finalAmt = calAmount(1000,0.30) // here we explicitly pass the dynamic rate that will override the default value.

    println(finalAmt)
}

fun calAmount(amount: Int, interestRate : Double = 0.40) : Int{ 
// Notice: Here you can see the default parameter that is directly assign.
    return (amount + amount * interestRate).toInt();
}

Output: 1300

Now the same concept in java we call it method overloading because name of function remain same but it is different by its parameter. The same logic in java we need to create a two function with single and double argument but in kotlin by default function have default value as parameter.

Now talk about the Java what happen when we call this function in java class.

public class JParameter {
    
    public static void main(String args[]){
        // You can see here we need to pass i.r because java doesn't now about the function overloading.
       int result = ParametersKt.calAmount(100,30); 
    }
}

But question is, if we want to pass only amount instead of amount and interest rate for that we need to use annotation in our kotlin file @jvmoverloads which is create a two function for us.

fun main(args: Array<String>){
    var finalAmt = calAmount(1000,0.30)

    println(finalAmt)
}

@JvmOverloads // <--------------- This is exact annotation used for create two function for java
fun calAmount(amount: Int, interestRate : Double = 0.40) : Int{
    return (amount + amount * interestRate).toInt();
}

// JParameter.java
public class JParameter {

    public static void main(String args[]){
        int result = ParametersKt.calAmount(100); // Now this would allow to use it and it will call the overloading feature.
    }
}

This is amazing feature of kotlin. Now kotlin has also provide us the named parameter. Means sometime we are using the function of class which is not design by us and when us we does't know the sequence of parameter. To simplify this kotlin allow as to write a name with parameter value.

fun calAmount(amount: Int, interestRate : Double = 0.40) : Int{ // <---- amount and interestRate is named parameter.
}

Now we got idea what is named parameter. When we call this function we can pass a parameter in any order but we can used the named parameter to pass it. This is new feature which is not there in java

 var finalAmt = calAmount(amount = 1000, interestRate = 0.30) //<---- Here is the magic you would allow to pass as named para.

//we can change the order of parameter if we use it. This will doesn't effect the kotlin automatically mapping it.
var finalAmt = calAmount( interestRate = 0.30, amount = 1000) 

@Bhavdip
Copy link
Author

Bhavdip commented Oct 8, 2017

String to Integer

In java we have Integer ParseInt for convert the value. we have StringValueOf for parse a string. Now what we have in kotlin for the same kind of thing.

fun main(args:Array<String>){

    var name : String = "4" //string

    var num : Int = Integer.parseInt(name) // string to integer but you know that we can call java method in kotline and kotlin in java
}

Now question is what is new in kotline regarding the same. kotlin provider method string.toInt() for return interger value

fun main(args:Array<String>){

    var name : String = "4"

    var num : Int = name.toInt() // thanks to kotlin they provide us toInt function help to convert the string to integer.

    println("${num * 10}")
}

Now you can see how kotlin push or help a java to make it better.

@Bhavdip
Copy link
Author

Bhavdip commented Oct 8, 2017

Try and Catch Exception How to handle the Exception in Kotlin

Below is the example of try catch block handle in the same way we did in java program. As we know we can write a java code in kotlin program.

fun main(args:Array<String>){

    var name = "Bhavdip"

    var number : Int = 0

    try{
        number = name.toInt() // this will throw exception
    }catch (e: Exception){
        println("Give proper Input")
    }
    println(number)

}
//This will throw the NumberFormatException exception.

Above is traditional approach for handle the exception. Lets we talk what is new in kotlin for handle the exception.
One is using expression. We know that expression return value. See below is the example using expression.

fun main(args:Array<String>){

    var name = "Bhavdip"

    var number : Int = try { // <------ this try catch block as expression it return the result and handle the exception.
            name.toInt()
    }catch (e: Exception){
        0
    }
    println(number)
}
Output: 0

@Bhavdip
Copy link
Author

Bhavdip commented Oct 8, 2017

Extension Function.

Consider an example like we have Alien class which as skills set and we print it.

//Alien.kt
class Alien {

    var skills : String? = null

    fun show(){
        println(skills)
    }
}
//FunctionExtension.kt
fun main(args:Array<String>){
    var val1 = Alien()
    val1.skills = "Java"
    val1.show()

    var val2 = Alien()
    val2.skills = "Kotlin"
    val2.show()
}

Now for example we want to add third person with having both skills. How to set/add the both/multiple skills set to new Alien person.
That can possible using extension in kotlin. See Alien.kt file it has only single method for show the skills but if you want to add multiple skill set we must have to add the new function plus/add new skills but consider like we don't have source code and still we want to it.

fun main(args:Array<String>){
    var val1 = Alien()
    val1.skills = "Java"
    val1.show()

    var val2 = Alien()
    val2.skills = "Kotlin"
    val2.show()
    
    var val3 = val1.plus(val2) // plus is not function in Alien class.
}

fun main(args:Array<String>){
    var val1 = Alien()
    val1.skills = "Java"
    val1.show()

    var val2 = Alien()
    val2.skills = "Kotlin"
    val2.show()

    var val3 = val1.plus(val2)
    val3.show()
}

fun Alien.plus(a : Alien) : Alien{ // <----This function is part of Alien but externally so it is consider as extension function.
    var newAlien : Alien = Alien() // new Alien object
    //assign new both skills here this refer val1 and a refer val2 while newAlien as newly created object
    newAlien.skills = this.skills + " " + a.skills  
    
    return newAlien
}

Output: 
Java
Kotlin
Java,Kotlin

@Bhavdip
Copy link
Author

Bhavdip commented Oct 8, 2017

Infix function(Using Infix Keyword) and operator overloading.

Infix function is what we previously seen its more like english language we call the function
For example. In loop section we noticed

for(index in nums){
}
Here in <-- Its infix function
 var nums = 1 until  16 //until is infix function

    for(index in nums){ //<--- In is infix function its simple english language but without bracket
        println(index)
    }

Lets consider our previous example: function as extension

var val3 = val1.plus(val2)  // we can use infix here
val3.show()

Before we remove the dot and bracket we should have to make our actual function as infix.

infix fun Alien.plus(a : Alien) : Alien{ // <----this now infix function.
    var newAlien : Alien = Alien() 
    //assign new both skills here this refer val1 and a refer val2 while newAlien as newly created object
    newAlien.skills = this.skills + " " + a.skills  
    return newAlien
}
//now we can call function in infix way
    var val3 = val1 plus val2
    val3.show()

Infix function take only one parameter . We have to define infix keyword in front of function. If you want to use operator overloading then use keyword operator overloading.

OperatorOverloading

var val3 = val1 + val2 //<--- here you can see we use sign(+) operator which is called plus function.
val3.show()

operator infix fun Alien.plus(a : Alien) : Alien{ // <----this now infix function with operator overloading
    var newAlien : Alien = Alien() 
    //assign new both skills here this refer val1 and a refer val2 while newAlien as newly created object
    newAlien.skills = this.skills + " " + a.skills  
    return newAlien
}

@Bhavdip
Copy link
Author

Bhavdip commented Oct 8, 2017

Recursion: function is call itself

fun main(args:Array<String>){

    var num = 7
    var factoral = 1

    for(i in 1..num){
        factoral = factoral * i
        println(factoral)
    }
}

Above is the factorial using for loops but how to get the same result using recursion function.

fun main(args:Array<String>){
    println(fact(num = 5)) //<--- we use parameter name.
}

fun fact(num : Int) : Int{
    if(num == 0)
        return 1
    else
        return num * fact(num - 1) ///<- this is the place where function is call itself.

}

Tail Recursion in Kotlin: For example in above example if we set num = 70,000 then we will get the exception of stackoverflow.
To overcome with exception we can use tail recursion.

fun main(args:Array<String>){
//    println(fact(num = 5))

    var num = BigInteger("70000")
    println(fact(num, BigInteger.ONE))
}

tailrec fun fact(num : BigInteger, result : BigInteger) : BigInteger{
    if(num == BigInteger.ZERO){
        return result
    }else{
        return fact(num - BigInteger.ONE, num*result)
    }
}

@Bhavdip
Copy link
Author

Bhavdip commented Oct 9, 2017

Constructor In Kotlin

In this topic we will look about constructor. In kotlin we can create a class same as java. See below example we have create a class Human with method think and we call it in main method. We got the output calling this method. Now question is how to call constructor?. In java we have constructor which is same as class name. But in kotlin we can't do like that.

class Human{
    fun think(){
        println("We think..")

    }
}
fun main(args:Array<String>){

    var humanObject = Human()
    humanObject.think()
}

In above we see we have call a method in main. Now we want to pass a parameter in constructor.

class Human(paramName : String) //<--- Constructor with parameter
{

    var name : String = paramName

    fun think(){
        println("We think..$name")

    }
}

fun main(args:Array<String>){

    var humanObject = Human("Bhavdip")
    humanObject.think()
}

Kotlin is awesome because if you don't want to use keyword constructor then it is also fine. But if you want to use modifier then a keywords become compulsory.

class Human public constructor(paramName : String) //<--- Primary Constructor with public modifier 
{

    var name : String = paramName

    fun think(){
        println("We think..$name")

    }
}

fun main(args:Array<String>){

    var humanObject = Human("Bhavdip")
    humanObject.think()
}

Below I call constructor without passing a value now in this case as we have seen previously we can set default value which is provided by kotlin. Refere in Name and Parameter chapter

class Human public constructor(paramName : String = ""Bhavdip ) //<--- Primary Constructor with public modifier 
{

    var name : String = paramName

    fun think(){
        println("We think..$name")

    }
}

fun main(args:Array<String>){

    var humanObject = Human()
    humanObject.think()
}

Can I create a constructor inside a class? First whatever we use in above example it is called primary constructor. The thing we want to create it is second constructor. Alternative you can call init which is called when a class is load see that example first.

class Human constructor(paramName : String)
{

    var name : String = ""
    
    init {                                        // see this init method which is called when class is load and we have assign a value in this block.
        name = paramName
        println("We get a parameters")
    }

    fun think(){
        println("We think..$name")

    }
}

Now this time we will see how to create a secondary constructor. Why we need a secondary constructor as we seen in case if you want to more than one parameter in constructor for that we can use it.

Note: If we call/create secondary constructor then must have expect to call primary constructor. for do that we can use it constructor chaining mechanism using this keyword.


class Human constructor(paramName : String="Kishan") //<-- we used Default name parameter value
{

    var age : Int = 0
    var name : String = paramName
//
//    init {
//        name = paramName
//        println("We get a parameters")
//    }


    constructor(age : Int, name : String) : this(name){   //<---- this is secondary constructor that called it from main method.
         this.age = age
         this.name = name
    }

    fun think(){
        println("We have create a human..$age with the name $name")

    }
}

fun main(args:Array<String>){

    var humanObject = Human(10, "Bhavdip") // this the spot it is called secondary constructor.
    humanObject.think()
}

@Bhavdip
Copy link
Author

Bhavdip commented Oct 9, 2017

Inheritance in Kotlin

As we seen we know how to create a class and object of it. Then we have seen how to use constructor. Lets try to do a inheritance in kotlin. As we know in java we don't have multiple inheritance the same thing is here because kotlin is better version of java.

The rules we have in java the same is applicable for kotlin.

In kotlin a class is by default as final. So if we try to extend it then its show error we can't extends final class. Final keyword would not allow us to extends it.

Note kotlin we don't have extends keyword but we can use (:) for inheritance.

For inheritance we should show our intention for to using it keyword open keyword.

open class Human{

    fun think(){
        println("Real think")
    }
}

class Alien : Human(){
    
}

fun main(args: Array<String>){
    var human = Human()
    human.think()
}

Lets try multiple inheritance as we know kotlin code is converted into java byte code and java does not support multiple inheritance.

open class Human{

    fun think(){
        println("Real think")
    }
}

open class Computer{
    
}

class Alien : Human(), Computer(){         //<-- Error here we not allow multiple inheritance.

}

fun main(args: Array<String>){
    var human = Human()
    human.think()
}

Override method using inheritance:
Now we override a method from one class to another class same as we did in java. Most important point is in kotlin everything is by default final even if use override keyword it would not allow because it is final in parent class. The solution is use open keyword as we know we have to explicitly show that we want to inherit it for use it in kotlin.

open class Human{

    open fun think(){                //<-- we make it open for inhetiance
        println("Real think")
    }
}

class Alien : Human(){

    override fun think(){                    //we make it open now we can override it.
        println("Alien real think")
    }
}
fun main(args: Array<String>){
    var human = Human() // Human class
    human.think()

    var alien = Alien()  //Alien class 
    alien.think()
}

Call By reference in Kotlin

In above example how to pass reference of parent class and call parent method.


fun main(args: Array<String>){
    var human = Human() // Human class
    human.think()

    var alien : human = Alien()  //Alien that reference to human  
    alien.think()                           // this will not call parent class method? because we make it open and to call parent method we need parent object
}

Constructor Inheritance

Whenever we inheritance class its called super class constructor.

open class Student(ttSubject : Int = 6) {

    var totalSubject : Int = ttSubject

    init {
        println("I am student init block")
    }

    open fun work(){
        println("I am student so I have total $totalSubject subject")
    }
}
class CollegeStudent(clSubject: Int): Student(clSubject){  //<-- this will call the constructor of the parent class.

    init {
        println("I am college Student init block")
    }

    /*override fun work(){
        println("I am COLLAGE student so I have total 10 subject")
    }*/

}
fun main(args: Array<String>){
    var collegeStudent = CollegeStudent(3)  //<-- this is call the constructor of collage student that will pass the value to parent.
    collegeStudent.work()
}
Output:
I am student init block
I am college Student init block
I am student so I have total 3 subject

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment