Monday, 5 February 2018

Basic Syntax - Kotlin Programming Language If, Loop, Functions

Defining functions

Function having two Int parameters with Int return type:
fun sum(a: Int, b: Int): Int 
{
    return a + b
}


Function with an expression body and inferred return type:
fun sum(a: Int, b: Int) = a + b


Function returning no meaningful value:
fun printSum(a: Int, b: Int): Unit 
{
    println("sum of $a and $b is ${a + b}")
}


Unit return type can be omitted:
fun printSum(a: Int, b: Int) 
{
    println("sum of $a and $b is ${a + b}")
}


Defining variables

Assign-once (read-only) local variable:
val a: Int = 1  // immediate assignment
val b = 2   // `Int` type is inferred
val c: Int  // Type required when no initializer is provided
c = 3       // deferred assignment

Mutable variable:
var x = 5 // `Int` type is inferred
x += 1


Top-level variables:
val PI = 3.14
var x = 0
fun incrementX()
{
    x += 1
}


Comments

Just like Java and JavaScript, Kotlin supports end-of-line and block comments.
// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */
Unlike Java, block comments in Kotlin can be nested.


Using string templates

var a = 1
// simple name in template:
val s1 = "a is $a"
a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"


Using conditional expressions
fun maxOf(a: Int, b: Int): Int
{
    if (a > b) {
        return a
    } else {
        return b
    }
}


Using if as an expression:
fun maxOf(a: Int, b: Int) = if (a > b) a else b


Hello Reader
You can comment if any confusion in syntax or if need more explanation we'll reply you ASAP.
Thank you Safe & Happy Coding. :)

1 comment:

Kotlin Android Syntax (Collections, Class, Instance)

Using collections Iterating over a collection: for (item in items) {     println(item) } Checking if a collection con...