Subscribe Now

* You will receive the latest news and updates on your favorite celebrities!

Trending News

Blog Post

Kotlin variable declaration, conditional statement and looping
Beginner

Kotlin variable declaration, conditional statement and looping

What is Kotlin?

Google has announced Kotlin as a official language for Android Application Development in Google I/O 2017. Google surprised all android developers by this announcement. Than many developers has started work with Kotlin and fall in love with its concise syntax and safety. I am one of them.

Kotlin is a statically-typed language, developed by Jetbrains. With features like higher-order functions, lambda expressions, operator overloading, string templates, and more, Kotlin has a lot more to offer than Java. Because Java and Kotlin are highly interoperable, they can be used together in the same project.

Every programmer knows that for learning any programming language we need to learn syntax of that language and basics of that language like variables, conditional statements, functions. Here in this blog we will learn basics of Kotlin language.

How Kotlin works with Android?

Kotlin and JVM

 

How to declare variables in kotlin?

Variables can be declare using ‘val’ and ‘var’ keyword in kotlin. Now question is what is difference between ‘val’ and ‘var’.

1). val: val is same as the final modifier in java. As you should probably know that we can not assign to a final variable again but can change its properties. so Val is used to declare immutable variable.

Example:

val str:String = "Hello"

// now if you try to reassign value to "str"
str = "World" // this will show you error "val cannot be reassigned"


2). var: we can change the value of variable which is declared using ‘var’ keyword. So var is used to declare mutable variable.

Example:

var str:String = "Hello"
//we can change value of “str” if it is defined using ‘var’ keyword.
str = "World" //This will not generate any error


Some more examples for variable declarations:

val a: Int = 1 // readonly value
var x = 5 // `Int` type is inferred
var isSelected = false // Boolean variable
var isSelected:Boolean = false


Conditional statements:

If..else:

Kotlin if else ladder when

Example:

1. Simple If case:

var isSearching=false
    if(!isSearching)   isSearching=true

2. if else:

var maxValue: Int
val pValue=10
val qValue= 20
if (pValue> qValue) {
    maxValue = pValue
} else {
    max = qValue
}

 

Make a note that if you try to assign value to variable using if expression than compulsory you have to add else branch.

Note: Kotlin not support ternary operator (condition ? then : else) because kotlin if expression works fine in this case also.

Example:

val greater=If(10>20) true else false

 

When expression:

> When expression in kotlin has replace “Switch Case” which we are using in java and C like language. It matches its arguments with all branches sequentially until some branch condition is satisfied. Here, we can use when expression as a statement or as a expression. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored(same as if condition).

Example:

private fun getRandomNumberInRange(min: Int, max: Int): Int {
    if (min >= max) {
        throw IllegalArgumentException("max must be greater than min")
    }
    val r = Random()
    return r.nextInt(max - min + 1) + min
}
var mNumber=getRandomNumberInRange(0,10)

1). Simple when expression:

when(mNumber){
	0-> print(“Number = 0”)
	1-> print(“Number = 1”)	
	else-> {
		print(“Number = None”)
	}
}

Here else is same as default case in Switch statement. If when is use as expression than else in mandatory.

2). when with range or collections:

when(mNumber){
	0..5-> print(“Number = 0”)
	6-> print(“Number = 1”)	
	else-> {
		print(“Number = None”)
	}
}

3). When using branch combined with comma:

when(mNumber){
	0,1,2,5-> print(“Number = 0”)
	6-> print(“Number = 1”)	
	else-> {
		print(“Number = None”)
	}
}

4). When using smart cast:

fun getGender(isMale:Any)=when(isMale){
is True-> “Male”
Else-> “Female”
}

5). We can also replace when instead of if else if chain:

when(mNumber){
	mNumber.isOdd()-> print(“x is odd”)
	mNumber.isEven()-> print(“x is Even”)
	else->print(“x is not a Number”)
}

For Loop:

> For loop in kotlin is equivalent to the foreach loop.

Syntax:

for (item in collection) print(item)

Example:
for(I in 1..10){
     println(i)
}

//With array
for(i in arrayNumber.size){
     println(arrayNumber[i])
}

While loop:

while and do..while work as usual

while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null) // y is visible here!

Hope you like this blog. If you have any question please ask me in comments or you can message me on twitter and facebook also.

Summary

Popularity of kotlin is getting increase day by day. More people are now learning kotlin for android development and most of them giving positive reviews. Most important point is Kotlin is designed with Java Interoperability in mind which makes it unique and easy to learn.

Related posts

19 Comments

  1. Avatar
    scr888

    So put your own unique spin regarding your content. You can develop good content by doing the particular sphere of the website.

    Michael Jordan didn’t shoot slam dunks the period he collected a b-ball. https://918kiss.bid/downloads/78-download-918kiss-casino-games-all-in-one-ios-and-android

  2. Avatar
    188bet

    I’m truly enjoying the design and layout
    of your blog. It’s a very easy on the eyes which makes it much
    more enjoyable for me to come here and visit more often. Did you hire
    out a designer to create your theme? Exceptional work! http://www.mbet88vn.com

    1. Lokesh Desai
      Lokesh Desai

      no i made it my self

  3. Avatar
    188bet

    I like the valuable information you supply for your articles.
    I’ll bookmark your blog and take a look at once
    more right here frequently. I am quite sure I will be told many new stuff proper here!
    Best of luck for the next! http://www.mbet88vn.com

  4. Avatar
    Anonymous

    I am interested about cotlin

    1. Lokesh Desai
      Lokesh Desai

      ok i will try to add more blogs for kotlin

  5. Avatar
    newtown casino pc

    With havin so much conttent do you ever run into
    any problems of plagorism or copyright violation?
    My site has a lot of completely unjque content I’ve either created myself or outsourced bbut it appears a lot of it is poppingg
    it up all over the web without my permission. Do
    you know anny ways to help stop content from being stolen? I’d certainly
    appreciate it. http://forum.annecy-outdoor.com/suivi_forum/?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2FWww.Melekomonentalli.com%2Fimportant-life-lessons-online-gaming-taught-us%2F%3E918+kiss+brunei%3C%2Fa%3E

    1. Lokesh Desai
      Lokesh Desai

      no i don’t know any way to stop content from stolen. i will research on that and let you know soon

  6. Avatar
    www.yahoo.org

    Or possiЬly he likes bowling.? Lee continued. ?I heard someone say tһat while ʏou hеar tһᥙnder, that
    meɑns that G᧐d is bowling іn heaven. I wager he is really good at it.

  7. Avatar
    foloren torium

    Your place is valueble for me. Thanks!…

  8. Avatar
    foloren torium

    whoah this blog is excellent i love reading your articles. Keep up the good work! You know, many people are hunting around for this information, you can aid them greatly.

  9. Avatar
    Martina Sotto

    Way cool! Some very valid points! I appreciate you writing this article plus the rest of the website is extremely good.

  10. Avatar
    minecraft

    Hi! This is my first visit to your blog! We are a collection of volunteers and starting
    a new project in a community in the same niche.
    Your blog provided us valuable information to work on.
    You have done a outstanding job!

  11. Avatar
    seo

    Nice post! Thank you.

  12. Avatar
    Lakseolie til hunde

    This is one awesome blog post.Really thank you! Keep writing.

  13. Avatar
    Dealing With Hemorrhoids

    Thanks for sharing your info. I really appreciate
    your efforts and I am waiting for your next write ups thank you once again.

  14. Avatar
    Healing Hemorrhoids

    I am not sure where you are getting your information, but good topic.
    I needs to spend some time learning more
    or understanding more. Thanks for wonderful info I was looking
    for this info for my mission.

Leave a Reply

Required fields are marked *

Copywrite @Android4Dev