NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

Kotlin – Advance Topics
- Object Oriented Programming
- Kotlin Standard Library
- Functional Programming
- Scope function & Extension function
- Operator Overloading
- Kotlin typing system
- Concurrency in Kotlin




Object Oriented Programming
Kotlin is an object oriented programming language just like Java. Object oriented programming (OOP) allows us to solve the complex problem by using objects. In this guide, we will learn what is a class, what is an object and several other features of Object Oriented Programming (OOP).



OOP – Concepts
● Class and Objects
● Kotlin Constructors
● Visibility Modifiers
● Kotlin Inheritance
● Kotlin abstract class
● Kotlin Interfaces
● Nested and Inner Class
● Kotlin Data Class
● Kotlin Enums Class
● Kotlin Sealed Class
● Companion Objects for "Static" Members
● Object Declarations as Singletons
● Packages and Imports
● Generic Classes
● Generic Functions
● Covariance
● Overriding Rules

Kotlin Class
Classes are the main building blocks of any object oriented programming language. All objects are part of a class and share the common property and behavior defined by the class in form of data members and member functions respectively.
A class is like a blueprint for the objects.
A class is like a prototype for objects which you can create by grouping methods and variables

Kotlin Object
Objects use the properties and behaviors of the class. As mentioned above, class is just a blueprint, no memory is allocated to the class. Once the objects of the class are created they take memory space and perform various actions on the data using data members and members functions of the class.

Access modifiers

Access modifiers are specified before the class, function and class properties.
Access modifiers:
private – Can be accessed inside the class only.
public – Can be accessed everywhere.
protected – Can be accessed to the class and its subclasses.
internal – Can be accessed inside the module.

Kotlin Constructors

The main purpose of constructor is to initialize the properties of a class. Constructor is called when we create the object of a class.
Types of Constructor
1. Primary Constructor
A primary constructor is the easiest way to initialize the class. It is declared as part of the class header.
2. Secondary Constructor
Secondary constructor in Kotlin is created using the constructor keyword. They play major role in inheritance.

Kotlin Inheritance

Inheritance is a feature using which a class inherits all the features of another class. The class from which the features are inherited is known as base class or super class or parent class and the class that inherits the features is known as derived class or sub class or child class.
By default all classes in Kotlin are final so
you have to use the open annotation in the
parent class, this tells the compiler that
this class can be inherited by other classes.


Visibility Modifier

Visibility modifiers restrict the access of classes, interfaces, functions, properties, constructors etc. to a certain level.
Kotlin Visibility Modifiers
● public: visible everywhere, this is the default visibility modifier in Kotlin which means if you do not specify the modifier, it is by default public.
● private: visible inside the file containing the declaration. If a data member or member function is declared private in a class then they are visible in the class only.
● protected: Visible inside class and subclasses.
● internal: visible inside the same module.

Abstract Class

An abstract class cannot be instantiated, which means we cannot create the object of an abstract class. Unlike other class, an abstract class is always open so we do not need to use the open keyword.
Points to Note:
1. We cannot create the object of an abstract class.
2. Property and member function of an abstract class are by default non-abstract. If you want to override these in the child class then you need to use open keyword for them.
3. If a member function is abstract then it must be implemented in the child class. An abstract member function doesn’t have a body only method signature, the implementation is done in the child class.


Interfaces

Similar to an abstract class, an interface cannot be instantiated because it doesn’t have any constructor.
Points to Note:
1. An interface can have both abstract and non-abstract function.
2. An interface can only have abstract property (data member), non-abstract properties are not allowed.
3. A class can implement more than one interfaces.
4. All abstract properties and abstract member functions of an interface must be overriden in the classes that implement it.

Nested class - Inner class

Nested class
When a class is declared inside another class then it is called nested class.
A Nested class cannot access the members of the outer class.
Inner class
Kotlin inner class is declared using inner modifier. Inner classes have access to the members of the outer class.



Data class

In Kotlin, you can create a data class to hold the data. The reason why would you want to mark a class as data is to let compiler know that you are creating this class for holding the data, compiler then creates several functions automatically for your data class which would be helpful in managing data.
Automatically generated functions for data class
1. equals()
2. hashCode()
3. toString()
4. copy()
5. componentN()



Data class functions

hashCode(): If two objects are equal in kotlin then they have the same hash code
equals(): If the hashCode() of two objects are equal then equals() returns true or false.
copy(): copy few of the properties of other objects
toString(): Methond can returns the String representation of an object.
componentN(): Method of data class destructure an object into a number of variables.

Enum

When we had to represent a constant set of possible options, a classic choice was to use Enum.
Enums have supporting functions like valueOf, values or enumValues what makes them easier to iterate over or serialize.

Sealed class

A sealed class is used for representing restricted class hierarchy where an object or a value can have one of the types from a limited set of values. You can think of a sealed class as an extension of enum class.
Sealed classes are abstract classes with a concrete number of subclasses all defined in the same file.
Rules of a Sealed class in Kotlin
1. We cannot create the object of a sealed class which means a sealed class cannot be instantiated.
2. All the subclasses of a sealed class must be declared within the same file where the sealed class is declared.
3. The constructor of sealed class is by default private and we cannot make it non-private.

Companion object
A companion object is initialized when the class is loaded in a thread-safe manner.
If you need to write a function that can be called without having a class instance but needs access to the internals of a class, you can write it as a member of a companion object declaration inside that class.

Singleton Class

Singleton Pattern is a software design pattern that restricts the instantiation of the class to only “one” instance.
So, to implement the Singleton pattern, we make a singleton class.
Properties of Singleton Class
● Only one instance: The singleton class has only one instance and this is done by providing an instance of the class, within the class. Also, outer classes and subclasses should be prevented to create the instance.
● Globally accessible: The instance of the singleton class should be globally accessible so that each class can use it.



Generics Class

Kotlin provides higher order of variable typing called as Generics. Implementation wise, generics is pretty similar to Java but Kotlin developer has introduced two new keywords “out” and “in” to make Kotlin codes more readable and easy for the developer.
Generally, in Kotlin generics is defined by <T> where “T” stands for template, which can be determined dynamically by Kotlin complier.


Covariance & Contravariance

A covariance class is a generic class where subtyping is preserved. Making a type parameter of a covariant class makes it possible to pass values of that class as function arguments and return values when the type arguments don’t exactly match the ones in the function definition.
In Kotlin, to declare the class to be covariant on a certain type parameter, you put the out keyword before the name of the type parameter to produce the element type.
In Kotlin, to declare the class to be contravariant on a certain type parameter, you put the in keyword before the name of the type parameter to consume the element type.


Kotlin Standard Library

The Kotlin Standard Library provides living essentials for everyday work with Kotlin.
These include:
● Higher-order functions implementing idiomatic patterns (let, apply, use, synchronized, etc).
● Extension functions providing querying operations for collections (eager) and sequences (lazy).
● Various utilities for working with strings and char sequences.
● Extensions for JDK classes making it convenient to work with files, IO, and threading.


Advance Kotlin

● Functional Programming Advance
● Lambdas
● Higher Order Functions and Member References
● Standard Library API
● Extension Functions
● Receiver Functions
● Inline Functions
● Generics
● Reified Generics
● Operator Overloading
● Delegated Properties
● Kotlin Type System
● Concurrency in Kotlin
● Coroutines Explained
● Building Coroutines


Functional Programming

● Pure functions
● Immutability
● Lazy initialization
● Function as First-class Citizen
● Lambda Expression
● Higher order function
● Function type
● Functional vs Imperative Paradigm


FP – Pure function

A pure function is a function that just operates over it’s input arguments to provide a result. It has no side effects, which means that the function itself is not provoking any external effects that you cannot control or you don’t expect. It’s not modifying any external state behind the scenes.


FP – Immutability

Kotlin is not a pure FP language and does not have a ‘default’ for mutable vs immutable. It gently encourages immutability in a few places by choice of syntax, but otherwise makes you choose each and every time.

FP - Lambda Expression

A function with no name is called an anonymous function. Lambda expressions are similar to anonymous functions consisting of a block of statements to be executed. Kotlin Lambdas are very similar to Java Lambdas. The syntax of a lambda expression is

FP - Higher Order Functions
Kotlin has support for higher order functions. A function is a higher order function if it can do at least one of the following things:
● Accept another function as an argument.
● Return a function.

FP - Function types
In Kotlin every function has a function type. Kotlin uses function types to represent the type of function. The function type is based on its parameters and return type. The function type is indicated with a parenthesized parameter type list and an arrow to the return type.
The syntax of function type is
(parameter1Type, parameter2Type) -> returnType
On the left-hand side, it contains parameters between the parenthesis and on the right-hand side it has the return type, both are connected by an arrow

FP - functions as first-class citizen
In Kotlin, functions are first-class citizen. It means that functions can be assigned to the variables, passed as an arguments or returned from another function. While Kotlin is statically typed, to make it possible, functions need to have a type.

Scope Functions

The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name. Such functions are called scope functions.
There are five of them:
let, run, with, apply, and also

Extension Functions

Extension function in Kotlin allows to define a method outside of the main class. We will be able to add or remove some method functionality even without inheriting or modifying them. Extensions are resolved statistically. It does not actually modify the existing class, but it creates a callable function that can be called with a dot operation.


Generic functions

Not only classes can have type parameters. Functions can, too. Type parameters are placed before the name of the function


Receiver Function

Any block of code in Kotlin may have a (or even multiple) types as a receiver, making functions and properties of the receiver available in that block of code without qualifying it.

Inline Functions

When using lambdas, the extra memory allocations and extra virtual method call introduce some runtime overhead. So, if we were executing the same code directly, instead of using lambdas, our implementation would be more efficient.
With inline functions in Kotlin we can have both abstraction and efficiency.
When using inline functions, the compiler inlines the function body. It substitutes the body directly into places where the function gets called. By default, the compiler inlines the code for both the function itself and the lambdas passed to it.

Inline Functions - No Inline

By default, all lambdas passed to an inline function would be inlined, too. However, we can mark some of the lambdas with the noinline keyword to exclude them from inlining.

Inline Functions - Inline Reification

As we saw earlier, Kotlin erases the generic type information at runtime, but for inline functions, we can avoid this limitation. That is, the compiler can reify generic type information for inline functions.
All we have to do is to mark the type parameter with the reified keyword

Reified Generics in Kotlin

● Generics on the JVM are normally implemented through type erasure, meaning generic type arguments of a function is not preserved at runtime. To solve this, Kotlin may use a reified type parameter that can only be used with inline functions.
● When an inline function is compiled, its bytecode along with the bytecode of a lambda passed to the function is inserted directly into the code of the calling function to prevent overhead. The effect is that you can pass functions through parameters in a way that the type arguments can’t be erased, or reified.

Operator Overloading in Kotlin

In Java, operators are tied to specific Java types. For example, String and numeric types in Java can use the + operator for concatenation and addition, respectively. No other Java type can reuse this operator for its own benefit. Kotlin, on the contrary, provides a set of conventions to support limited Operator Overloading.

Delegated Properties

Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object. The following example demonstrates how this happens in Kotlin.

Kotlin typing system

Kotlin typing system is amazingly designed. It gives us very comfortable nullability support, type inference, universal guards, and much more.
non-nullable can be used as nullable. This is possible because there is a relation between those two types. A nullable type is a supertype of non-nullable.

Concurrency in Kotlin

Kotlin/Native runtime doesn't encourage a classical thread-oriented concurrency model with mutually exclusive code blocks and conditional variables, as this model is known to be error-prone and unreliable. Instead, we suggest a collection of alternative approaches, allowing you to use hardware concurrency and implement blocking IO. Those approaches are as follows, and they will be elaborated on in further sections:
● Workers with message passing
● Object subgraph ownership transfer
● Object subgraph freezing
● Object subgraph detachment
● Raw shared memory using C globals
● Atomic primitives and references

Concurrency - Non-blocking

Threads are heavy, expensive to create, and limited—only so many threads can be created—So when a thread is blocked it is, in a way, being wasted. Because of this, Kotlin offers what is called Suspendable Computations; these are computations that can suspend their execution without blocking the thread of execution. So instead of, for example, blocking thread X to wait for an operation to be made in a thread Y, it’s possible to suspend the code that has to wait and use thread X for other computations in the meantime.
Furthermore, Kotlin offers great primitives like channels, actors, and mutual exclusions, which provide mechanisms to communicate and synchronize concurrent code effectively without having to block a thread.


Coroutines

Coroutines = Co + Routines
Here, Co means cooperation and Routines means functions.
It means that when functions cooperate with each other, we call it as Coroutines.
A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously.
On Android, coroutines help to manage long-running tasks that might otherwise block the main thread and cause your app to become unresponsive.

Coroutines Features

Coroutines are recommended solution for asynchronous programming on Android.
Lightweight: You can run many coroutines on a single thread due to support for suspension, which doesn't block the thread where the coroutine is running. Suspending saves memory over blocking while supporting many concurrent operations.
Fewer memory leaks: Use structured concurrency to run operations within a scope.
Built-in cancellation support: Cancellation is propagated automatically through the running coroutine hierarchy.
Jetpack integration: Many Jetpack libraries include extensions that provide full coroutines support. Some libraries also provide their own coroutine scope that you can use for structured concurrency.

     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.