Skip to content

Instantly share code, notes, and snippets.

@Bhavdip
Last active October 9, 2017 04:46
Show Gist options
  • 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 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