In this article, I want to focus on foundational knowledge to understand languages I am using very deeply. I will update this article frequently

Java

Variable Arguments (Varargs)

public static void fun(int ... a) 
{
   for (int i: a){
//do something
}

int arr[] = a
} 

Lamda

The lamda function expressions are just anonymous functions basically which allow as to define a function very concisely at the place where we need it.
1. Functional Interface (Single Abstract Interface (SAM) )
A functional interface is an interface that contains only one abstract method. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface

2. The Arrow Operator
Lambda expressions introduce the new arrow operator -> into Java. It divides the lambda expressions in two parts:
The parameters -> the lambda body

With functional interface and arrow operator concepts in mind, you can put together a simple lambda expression

Thread Interference

Thread interference in java is a condition which occurs when more than one threads, executing simultaneously, access same piece of data. When more than one threads have access to same data, it is possible that data may get corrupted or one may not get the desired output. Thread interference occurs when code written is not thread safe.

public static void main(String[] args) {
    final Counter counter = new Counter();
    new Thread() {
        public void run() {
            counter.increase();
        };
    }.start();

    new Thread() {
        public void run() {
            counter.decrease();
        };
    }.start();
}

public static class Counter {

    private int count;

    public void increase() {
        count++;
    }

    public void decrease() {
        count--;
    }

}

1. Thread 1: read value of count from memory (value of count = 0)
2. Thread 2: read count from memory (value of count = 0)
3. Thread 1: increase value of count (value of count = 1)
4. Thread 2: decrease value of count (value of count = -1)
5. Thread 1:count = 1
6. Thread 2:count = -1

How To Avoid Thread Interference or How To Acheive  Thread Safeness?

  • By declaring the method as synchronized. (Making Counter() as synchronized)
  • By declaring the variables as final.
  • By declaring the variable as volatile.
  • By creating the immutable objects.
  • By using Atomic operations.
  • By restricting the access to same object by multiple threads. (creating object of Counter for each thread)

Memory Consistency Errors

Volatile

Synchronized

Synchonized method

Synchonized statement

Atomic access

Kotlin

var, val

var is short for variable
val is short for value. val is same as final in java. That means it is read-only (but not immutable)  but its properties can be changed.
var has both a getter and a setter, whereas valonly has a getter.

fun copyAddress(address: Address): Address {
    val result = Address() // result is read only
    result.name = address.name // but not their properties.
    result.street = address.street
    // ...
    return result
}

Mutable and Immutable

The main purpose of immutable objects is to prevent accidental modification and side effects, thus reducing chances of bugs. They can make concurrent programming way safer and cleaner (most of the notoriously hard to find concurrency bugs are ultimately caused by mutable state shared between threads).

Immutable is good,simple and offer benefits in concurrent programming. So why people keep using mutable. Well, back to the way an immutable object work. Whenever you do something with an immutable object you actually do with its copy that’s why immutable can avoid us run into synchronization problems and that is why we dont use it for large and/or complex objects or any situation that creating a new copy of the object for every single change can be very costly.

  • What is different between Immutable and read-only

    Readonly Immutability
    Readonly is set on the reference to an object Immutability is a property of the object itself.
    readonly means that the reference cannot be changed -> do whatever as long as reference not changed Immutable mean object cannot be changed
    interact with object  interact with a copy of object

     

Funtional Programming

To avoid side effect in Kotlin, Funtional Programming is just one of concepts you can use besides we have Object-oriented concept for instances, we have immutability

Higher order function

lets you pass functions as parameters as well as return functions. Check out a high order function in below snippet:

fun main(args: Array<String>) {
    var a = 2
    println(someMethod(a, {println("Just some dummy function")}))
}
fun someMethod(a: Int, func: () -> Unit):Int {
    func()
    return 2*a
}

Inline Function

Higher order function lets you pass functions as parameters as well as return functions. But the fact that they are stored as objects may make the use disadvantageous at times because of the memory overhead. The thing is, each object is allocated space in memory heap and the methods that call this method are also allocated space.
So there is a way to get around the memory overhead issue is, by declaring the function inline

inline fun someMethod(a: Int, func: () -> Unit):Int {
    func()
    return 2*a
}

Basically inline tells the compiler to copy these functions and parameters to call site.
Inline can be used when we wish to reduce memory overhead. But inline also increases the resulting bytecode. Which is why inline usage should be avoided with large functions or accessors with large code logic.

Lazy evaluation

Lazy evaluation is a major concept in all pure functional programming languages . It allows us to evaluate an expression as far as necessary.

Sequence

val list = listOf(1, 2, 3, 4, 5, 6)
val result = list.asSequence()
        .map{ println("In Map"); it * 2 }
        .filter { println("In Filter");it % 3  == 0 }
println("Before Average")
println(result.average())

Let’s see the result


Before Average
In Map
In Filter
In Map
In Filter
In Map
In Filter
In Map
In Filter
In Map
In Filter
In Map
In Filter
9.0

It is lazy, doesn’t want to do any work until a Terminal is connected to it. A Terminal is like an operation that will result something e.g. sum, average, first, etc….

  • When no operation needed, use List
  • When there’s Map operation only, use Sequence
  • When there’s Filter operation only, use List
  • If it ends with First, use Sequence.

Visibility Modifier

Modifier Package Class and Interface Contructor
public(default) visible everywhere visible to any client who can see the declaring class visible everywhere where the class is visible
private visible inside the file containing the declaration visible inside the class only visible everywhere where the class is visible
internal visible everywhere in the same module (a set of Kotlin files compiled together) visible inside the class and its subclasses  visible everywhere where the class is visible
protected not available for packages (used for subclasses) visible to any client inside the module that can see the declaring class  visible everywhere where the class is visible

note: To specify a visibility of the primary constructor of a class, use the following syntax (note that you need to add an explicit constructor keyword):

class C private constructor(a: Int) { ...

Generic

First I want to talk a bit about what generic classes/functions are and why you would use them. So the name already implies a generic class/function allows you to write a class/function in a more generic way so that they can also be used in more different situations

To truly understand generics, first we need to understand three main concepts:

  • class vs type
  • subclass vs subtype
  • variance: covariance, contravariance and invariance

First thing make you realize a generic class/function is that the generic type parameters in angle brackets <>

Generic Classes

class TimeLine&amp;amp;lt;E&amp;amp;gt; {
    val date2Data: MutableMap&amp;amp;lt;Date,E&amp;amp;gt; = mutableMapOf()
    fun add(element: E){
        date2Data.put(Date(),element)
    }
    fun getLatest(): E{
        return date2Data.values.last()
    }
}
}

usage

 val timeLine: TimeLine&amp;amp;lt;Int&amp;amp;gt; = TimeLine()
        timeLine.add(2)
        timeLine.getLatest()

Generic Function

 

class vs type

In Java and Kotlin all classes have at least one type that is the same as the class, for example: an Interger is a class and at the same time a type.

On the other hand, in Kotlin we also have nullable types, consider String? we can’t really say that String? is a class, because notionally, it is still a String.

Another example in Java and Kotlin is List.

List is a class, but List<String> is not a class, it’s a type.

The following table summarizes these examples:

 

Variance

A nature, universe, science, music, love lover

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami