Kotlin all the Essentials that you need to know.


Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of Kotlin's standard library depends on the Java Class Library, but type inference allows its syntax to be more concise. Wikipedia
Filename extensionskt,.kts,.ktm
First appeared22 July 2011; 9 years ago
Typing disciplineInferred, static, strong

Configure Kotlin in Project 
Tools >  Kotlin  > 

Variables 

  • var - Mutable 
  • val - Immutable 

All declarations in Kotlin are non null by default 

Nullable and Non-Nullable DataTypes 
  • var notNullable : String = "Value"
  • var nullable : String? = null 
Handling Null in Kotlin
  • Safe Call ?. 
  • Not Null Assertion Operator !!. (Bang)
  • Elvis Operator ?:
*This operator will throw Null Pointer Exception 

* Use Kotlin Interpreter to Code + Run + Test your Kotlin code 


List, MutableList 
var myList = listOf( list1, list2 )
Arrays 
var products = arrayOf("product1", "product2")
For Loop : ForEach 


if-else 
When 
Functions 



Filter 
Lambdas : Function with no name is called Lambda 
var lambda  = { x : Int -> x*2}

Higher Order Function 
Any function that takes arguments as function 


Object Oriented Terminology 
  • Class : Object Blueprint (Shop Plan)
  • Object : instance of Class ( Actual Shop)
  • Property : Class characteristics (Shop size, products present)
  • Method : Class function ( manageProducts(), displayProducts() )

Class Visibility 
  • public : by default 
  • private : Subclass can't see , only inside same class 
  • protected : same as private but subclass can see it  if property is private 
  • internal : anywhere in same module/project 
Constructors : 
  • Primary Constructor 
  • Secondary Constructor : if we declare secondary constructor we have to use this( pass properties)
* If property is created we use (val or var) which is accessable other not 
* Always use Primary Constructor and try to use helper method to create secondary constructor 



init {
        // used to initialise property of the class 
        // executed before constructor of the class 
}

Inheritance 
  • use open keyword 
  • override the method or property 
Interface 
  • can't be instantiated 
  • no constructor 
  • consist of all the general implementations of methods 
Class Types 

Abstract Class : 
  • we can't make instance of abstract class directly, 
  • it can have constructors, 
  • we use abstract class mostly for features, 
  • we don't need to use open keyword 
Singleton Class: 
  • Class with exactly only one instance and used everywhere 
  • Ex. Network Service, Database Service 
Data Class: 
  • Class whose main purpose is to hold data 
  • primary constructor need to hold at least one property 
  • all property need to be marked as var or val 
  • they cannot be abstract, open, sealed or inner 
Enum Class 
  • use to implement type-safe enums
  • each enum constant is an object and separated by comma
  • you can give them properties or even methods 
enum class Direction {
    NORTH, SOUTH, WEST, EAST
}

enum class ProtocolState {
    WAITING {
        override fun signal() = TALKING
    },

    TALKING {
        override fun signal() = WAITING
    };

    abstract fun signal(): ProtocolState
}


Sealed Class 
  • it is abstract by default 
  • can subclass in only 1 file not in another file 
  • it is the safest way to represent fixed number of types
  • We mostly use seal class in when because it verify all the cases so else is not required 


Kotlin Advance Topics 

Pairs 
  • Kotlin datatype that allows us to define generic pairs of values 
  • We can make chain calls 
  • Also we can deconstruct pairs : Take apart an object and assign it to multiple variables 
  • Usually it is used to return more than 1 values form a function 
Collections 
  • reverse list : list.reversed()
  • add, remove, contains, sublist, sumBy     
Mapping 
  • Map<Key,Value> pairs     
Constants 
  • top level constants 
  • object level constants 
  • constants inside a class 
Companion Object 
  • they are initialised form the static constructor of the containing class 
  • they are created when object is created 
Object 
  • They are initialised lazily on the first access to that object. 
  • They are singleton, meaning Kotlin will instantiate exactly 1 instance of the class.  


Extension Function 
  • Extension function helps to create helper function 
  • Extension function are defined outside the class they extend, so they don't get access to private variables. 
  • You can also define Extension property too. 
  • Extension function can be called also in nullable variables or we can provide the default behaviour when your function is applied to null. 


Generics 


Generic Class 
  • With Generic Class we can hold any type of object 
  • WildCard which will fill any Types 
  • We can also specify the type of Generics 
  • To ensure parameter not null we can pass type Any  <T : Any> 

Generic In and Out 
  • Out Types can only be passed out of an object or returned 
  • In Types can be passed into an object 
  • In and Out Variance are only applied in Class and Interface 

Generic Function 
  • Type parameters are placed before the name of the function 
  • fun <T> functionName(item: T) : List<T> { }
  • To cal the function we specify the type argument after the name of the function 

Annotations 

  • Annotations are read by compiler and used to generate code or even logic 
  • It is a way of attaching metadata to code. 
  • @AnnotationName 

fun higherOrderFunction( name: String, operation: (String) -> String) {

}
with(property) {} : It performs actions to given property. 

run {} : It returns the result of function 

apply {} : It returns the object on which it is applied to. 

let {} : Particularly useful for chaining manipulations together. 


Inline : In order to reduce the memory overhead of such higher order functions or lambda expression we can use the inline keyword which ultimately requests the compiler to not allocate memory and simply copy the inlined code of that function at the calling place. 

  • Without inline an object is created every call 
  • With inline no new object is created 




Thanks for Reading !! 












Comments

Popular Posts