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!!

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...