Friday, 24 April 2020

Visibility Modifier In Kotlin


Visibility Modifier

The visibility modifier basically defines a scope from where it can be visible and accessible. There are four visibility modifiers provided by the Kotlin.
  • private 
  • protected
  • internal 
  • public
The default visibility modifier is public.

Note: We can't use the visibility modifier with Local variables,  Local functions, and Local classes. Here is the code snippet that is self-explanatory:

    private class Number() {

        private fun add() {
            // Can't use visibility Modifier here with class declaration
            private class numberFloat{...}

            // Can't use visibility Modifier here with local function
            private fun addFloat() {...}
        }
    }


Private:

The scope of the private modifier is the containing class only. It's visible and accessible only inside the file/ class where it is declared. The code snippet explain it more:

TestPrivate.kt file

// Visible and accessible only inside this file
private const val two: Int = 2

// Visible and accessible only inside this file
private class Number() {

    // Visible and accessible only inside the Number class
    private val seven = two + 5
}

// ERROR: seven is not accessible outside the Number class
private const val nine = seven + two


Protected:

The scope of the protected modifier is the containing class along with its sub-classes, no matter where these sub-classes are declared. If you have used java before, that even does not allow it in the different packages.

Note: This modifier is not allowed for top-level declarations and inside the object class.

Here is a code snippet that will show the usage of the protected modifier.

TestProtected.kt file

// ERROR: protected modifier is not allowed at top-level declarations
protected const val three: Int = 3

// ERROR: protected modifier is not allowed at top level declarations
protected class HelloWorld(){...}

// Visible and accessible only inside this file
private const val two: Int = 2

// Visible and accessible only inside this file
private open class Number {

// Visible and accessible only inside the Number class and it's subclasses
    protected val seven = two + 5
}

// Visible and accessible only inside this file
private class NumberFloat : Number() {

    // seven is accessible because NumberFloat is a subclass of Number
    private val num: Float = two + 7.5f + seven
}

// ERROR: num and seven is not accessible here
private val test = num + seven


Internal:

The scope of the internal modifier is the module where the declaration file exist. It'll not be visible to any other module even if the declaration file is accessible to that module. 

A module is a bunch of Kotlin files that compiled together, like:

  • An IntelliJ IDEA project or module
  • A Maven project or module
  • A Gradle project or module

For Example: 

If we have a gradle project and we have two module as presentation module and data module in the project. If we have AppConstant.kt in presentation module and ApiConstant.kt in data module. If we'll try to access internal variable from ApiConstant.kt to AppConstant.kt then it will not be accessible, even If ApiConstant.kt is accessible in presentation module. Here is the code snippet that will clear the things more:

ApiConstant.kt file in data module

object ApiConstant {
    
    internal const val PARAM_USERNAME = "username"
}

AppConstant.kt file in presentation module

object AppConstant {
    
    // PARAM_USERNAME is not accessible in different module
    const val USERNAME = ApiConstant.PARAM_USERNAME 
}


Public:

The public modifier is accessible to code where the declaration class/ file is accessible. The default visibility modifier in Kotlin is public. It is like internal modifier with some extra accessibility. In the above example if PARAM_USERNAME would be public then it would be accessible to AppConstant.kt. Here is the code snippet:


ApiConstant.kt file in data module

object ApiConstant {
    
    // public is default visibility modifier so we can remove it.
    public const val PARAM_USERNAME = "username"
}

AppConstant.kt file in presentation module

object AppConstant {
    
    // PARAM_USERNAME is accessible in different module
    const val USERNAME = ApiConstant.PARAM_USERNAME 
}


I think we have taken enough knowledge about visibility modifier in Kotlin now.
Happy Learning!!

Thursday, 9 April 2020

Loops In Kotlin

Loops

The loops in Kotlin are similar to other programming languages. Loops basically provide the flexibility to iterate over any kind of data structure.

For Loop

To iterate over any data structure, It should be iterable. for loop always implicitly declares a new read-only variable in its scope and it's not accessible outside the loop scope. Here is a code snippet that will clear the things more:

val names = listOf("Ram", "Syam", "Geta")
for (name in names) {
        println(name)  // Print the names present in the 
}

 println(name) // name is not available outside the loop scope

Output:
Ram
Syam
Geta


  • We can also get the index along with the value while iterating by for loop. Here is the code snippet:

 // first variable would be always index
for ((index, name) in names.withIndex()) { 
        println("index $index, name $name ")
}

Output:
index 0, name Ram 
index 1, name Syam 
index 2, name Geta 


  • Alternatively, We can also iterate an array or list using indices. Here is the code snippet that is self-explanatory:

for (index in names.indices) {
        println("name ${names[index]} ")
}

Output: 
name Ram 
name Syam 
name Geta 


  • There is another flexibility that we can use the range operator (..) to iterate the loop. Here is the code snippet that is self-explanatory:

for (number in 0..10) { // It would print from 0 to 10 along with 0 and 10
        print("$number, ")
}  

Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,



  • There is another flexibility that we can exclude the last value using until while iterating the loop. Here is the code snippet:

for (number in 0 until 10) { // It would print till 9
        print("$number, ")
}

Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 


  • There is another flexibility that we can control and specify the increment steps like increment by 2, so at every iteration, the increment would be 2. Here is the code snippet that is self-explanatory:

for (number in 0 until 10 step 2) { // step must be positive always
        print("$number, ")

Output: 0, 2, 4, 6, 8, 

Note: Step must be positive always otherwise you would get Runtime Exception: java.lang.IllegalArgumentException: Step must be positive, was: -2


  • There is another flexibility that we can iterate in the reverse order (count downwards), To achieve it we can use downTo. Here is the code snippet that is self-explanatory:

for (number in 10 downTo 0 step 2) {
        print("$number, ")
}

Output: 10, 8, 6, 4, 2, 0, 


  • We can also iterate the map using for loop. Here are various ways to iterate over the map. Here is the code snippet that is self-explanatory:

 val map = mutableMapOf(1 to "x", 2 to "y", 3 to "z")

// Iterating the map with every entry object
    for (entry in map) {
        print("${entry.key}: ${entry.value}, ")
    }

Output: 1: x, 2: y, 3: z, 

// Iterating the map with key and value objects
    for ((key, value) in map) {
        print("$key: $value, ")
    }

Output:  1: x, 2: y, 3: z, 

// Iterating the map with key objects
    for (key in map.keys) {
        print("$key, ")
    }

Object: 1, 2, 3, 

//Iterating the map with value objects
    for (value in map.values) {
        print("$value, ")
    }

Output: x, y, z, 

while and do..while Loop

In Kotlin programming language also while and do..while loop works like other programming languages. Here is the code snippet that is self-explanatory:

var num = 0

// while Loop
    while (num < 10) {
        print("$num, ")
        num++
    }


// do..while loop
num = 0
    do {
        print("$num, ")
        num++
    } while (num < 10)

Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 


I think we have gained enough knowledge regarding loops in Kotlin.

Happy Learning!!




Saturday, 4 April 2020

Variables In Kotlin

Variable Declaration In Kotlin

Mutable Variables - var


We can declare the mutable variable by using 'var' in the Kotlin programming language. We don't need to declare the type of the variable in the Kotlin programming language, It inferred the type when we initialize the variable. 

We must declare and initialize the variable at the same type to get the benefit, Otherwise, we have to provide the type of the variable at the time of declaration. If we'll try to declare the variable without initializing or providing the type then we'll get Syntax Error.

Some examples here:

// The variable must either have a type annotation or be initialized
var a   
        
// Immediate assignment of the variable
var a = 2

// Int type is inferred, no need to specify the type of variable
var a = 2     

//  Type required when no initializer is provided to the variable
var b: Int  

//  deferred assignment of the variable 
b = 3           

//  Reassigned the value
a = 5, b = 8  

Immutable Variables - val


These are Read Only variables and used to refer only one object. When we assign the value to these variables, we can not change or re-assign the value to these variables. These variables are used for assign-once only.

These variables are not constant. It can be initialized with the value of a variable and its value doesn't necessary to be known at compile time. if it's declared inside a construct that is invoked repeatedly like a function or loop, It can take a different value every time on each invocation.

These variables can not be re-assigned while it's in a scope. Also, these variables can refer to mutable objects like mutable collections.

Some examples here:

// Immediate assignment of the variable
val a = 2               

// String type is inferred, no need to specify the type of variable
val st = "String"  

//  Type required when no initializer is provided to the variable
var b: Int      

//  deferred assignment of the variable         
b = 3                 

// Int type is inferred, no need to specify the type of variable      
val num = 2           

// Can not reassign, Compile Time Error: Val can not be reassigned
num = 7                


Constants


These variables are truly constant variable, We can not re-assign the value to these variables like read-only variables (val). The difference is that its value should be known at compile-time necessarily. We can only declare these variables at the top level of a file or inside an object declaration (Singleton class in Kotlin), but not inside a class declaration.

Some examples here:

// Constant variable declaration
const val a = 9      

// Compile Time Error: Property must be initialized
const val b      

// Can not reassign       
a = 5                      

I think, Now we have enough knowledge of variables in Kotlin.

Happy Learning!!


Switch Case in Kotlin


Use Of 'when'


If you are familiar with any programming languages like C, C++ or Java, you might have heard the term switch statement, when there are multiple conditions and based on input we need to execute a condition. It's a replacement of multiple if-else statements. “when” operator matches the variable value against the branch conditions. If it satisfies the branch condition then it will execute the statement inside that scope. Here is a sample code snippet:

fun main(args: Array<String>) {

    val x:Int = 10   

    when (x) {
        1 -> println("x is 1")
        2 -> println("x is 2")
        else -> {
            println("x is neither 1 nor 2")
        }
    }
}

In the above sample, the Kotlin compiler matches the value of x with the given branch conditions. If it doesn't match any of the branches, then it will execute the else part. 'when' is equivalent to multiple if block. Kotlin provides another flexibility to the developer, where the developer can provide multiple checks in the same line by putting“,” inside the branches. Let us modify the above sample here:

fun main(args: Array<String>) {

    val x:Int = 10

    when (x) {
        1,2 -> println(" The value of X either 1,2")
        else -> {
            println("x is neither 1 nor 2")
        }
    }
}

There is another flexibility instead of using only constants, we can also use arbitrary expressions as a branch condition. Here is the code snippet:

fun main(args: Array<String>) {

    val x:Int = 10    
    val s: String = "10" 
   
    when (x) {
        parseInt(s) -> println(" The value of X is $s ")
        else -> {
            println("No Branch Found")
        }
    }
}

We can also use range as a branch condition using in and !in. Here is the code snippet:

fun main(args: Array<String>) {

    val x:Int = 10    
    
    when (x) {
        in 1..10 -> println(" Range 1 to 10")
        in 11..20 -> println(" Range 10 to 20")
        !in 10..20 -> println(" Range not in 10 to 20")
        else -> {
            println("Not in the range")
        }
    }
}

We can also check the particular type by using is and !is. Here is the code snippet:

fun main(args: Array<String>) {

    val x:Any = 100

    when (x) {
        is Int -> println(" Type is Int")
        is String -> println(" Type is String")
        !is Double -> println(" Type is not Double")
        else -> {
            println("No Type Found")
        }
    }
}

It can also be used as if-else if chain. If no argument is passed along with 'when' keyword, the branches condition would be boolean and the branch condition is executed when true. Here is the code snippet:

fun main(args: Array<String>) {

    val x:Int = 10   

    when {
        x.isOdd() -> println("x is odd")
        x.isEven() -> println("x is even")
        else -> {
            println("x is neither odd nor even")
        }
    }
}

We can also use enum along with 'when'. Here is the code snippet:

fun main(args: Array<String>) { 

    when (KotlinEnumTest.NORTH) {
        KotlinEnumTest.NORTH -> println(KotlinEnumTest.WEST)
        KotlinEnumTest.WEST -> println(KotlinEnumTest.NORTH)
        else -> {
            println("No Condition Matched")
        }
    }
}

enum class KotlinEnumTest {
    NORTH, SOUTH, WEST, EAST

}

One more thing, The scope of variables in 'when' subject would be restricted to 'when' body.

I think, Now we have enough knowledge about 'when' in Kotlin.

Happy Learning!!

Monday, 24 February 2020

Kotlin Introduction


Why did Google replace Java with Kotlin, and why only Kotlin but not other languages?


I'm going to give you a different answer. I believe it isn't the beauty of Kotlin that inspired Google to replace Java and only Java. There are many things to consider.

  1. Google has to get rid of Java, sooner or later. Since the time Oracle took control of Java and observed Google’s use of JAVA API in Android, it has been bombarding Google. The last lawsuit was about the commercial use of Java API: Oracle goes for appeal against Google. and Oracle Won: Happy as Larry: Why Oracle won the Google Java Android case. Java has become the Achilles heel for Google. Until the replacement, it’s going to be a very painful experience and spending millions of dollars on lawyers to hold on to something that may be lost anytime, NOT AN OPTION!!!
  2. Java has an ecosystem that is almost unmatched. Android programmers have been using Java and millions and millions of lines have already been developed. They can accept a new language but not accept losing the ecosystem. Augmenting that is the fact that the huge Android SDK is in Java, porting is more expensive than using a bridge so the language choices are limited to the ones that are either binary compatible with JAVA or can utilize the existing JAVA code in some way. Go, Dart languages which were made in Google’s kitchen are out!
  3. Scala, Closure run on the same JVM as Java and they can use existing JAVA code to some extent. However, JAVA is a procedural language while these other JVM languages support a different paradigm of programming, Functional. No matter how much die-hard fans tout about it, Functional programming is not the mainstream, adopting it is even more difficult with a very steep learning curve. Scala and Closure are out! and so is Groovy with it’s outlandish syntax and DSL style programming.
  4. A new language perhaps? Designing a new language is something Google didn’t find success with. Go and Dart got a poor reception from the programming community. In addition to that, designing new languages, its ecosystem, its supporting tool is a big endeavor, takes a lot of effort and time (Android Studio still needs many versions to be fully stable).
So Google has to find a permanent solution to this oracle Java problem. Once that let's them keep using Java and its ecosystem without any liabilities or worries. Enter the scene, Kotlin!!!, a shy, rugged clothed, and struggling procedural language that runs on JVM trying to make its presence known, for a few years, but nobody was listening.

Kotlin:

  • Kotlin is an Android-compatible language that is concise, expressive, and designed to be type- and null-safe. It works with the Java language seamlessly.
  • In Kotlin 1.1, we officially released the JavaScript target, allowing you to compile Kotlin code to JS and to run it in your browser. In Kotlin 1.2, we’re adding the possibility to reuse code between the JVM and JavaScript. Now you can write the business logic of your application once, and reuse it across all tiers of your application – the backend, the browser frontend, and the Android mobile app.
  • Kotlin helps concise the syntax and the user can concentrate on writing logics instead of syntax.

Advantages and Disadvantages

The following are some of the advantages of using Kotlin for your application development.

Easy Language − Kotlin is a functional language and very easy to learn. The syntax is pretty much similar to Java, hence it is very easy to remember. Kotlin is more expressive, which makes your code more readable and understandable.

Concise − Kotlin is based on JVM and it is a functional language. Thus, it reduces lots of boilerplate code used in other programming languages.

Runtime and Performance − Better performance and small runtime.

Interoperability − Kotlin is mature enough to build an interoperable application in a less complex manner.

Brand New − Kotlin is a brand new language that gives developers a fresh start. It is not a replacement of Java, though it is developed over JVM. It is accepted as the first official language of android development. Kotlin can be defined as - Kotlin = JAVA + extra updated new features.

The following are some of the disadvantages of Kotlin.

Namespace declaration − Kotlin allows developers to declare the functions at the top level. However, whenever the same function is declared in many places of your application, then it is hard to understand which function is being called.

No Static Declaration − Kotlin does not have usual static handling modifiers like Java, which can cause some problems to the conventional Java developer.

Happy Learning!!


Reference:
I was figuring out on the google and found the above content from various websites.

Visibility Modifier In Kotlin

Visibility Modifier The visibility modifier basically defines a scope from where it can be visible and accessible. There are four visi...