Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Return

fun main(args: Array<String>) { 
   var x:Int=10 
   println("The value of X is--"+doubleMe(x)) 
} 
fun doubleMe(x:Int):Int{ 
      return 2*x; 
}

Do While

fun main(args: Array<String>) { 
   var x:Int=0 
   do{ 
       x=x+10 
       println("I am inside Do block---"+x) 
   }while(x<=50) 
     
} 

While

fun main(args: Array<String>) { 
   var x:Int=0 
   println("Example of While Loop--") 
   while(x<=10){ 
       println(x) 
       x++ 
   } 
     
}

Library Function

fun main(args: Array<String>) { 
    val items = listOf(1, 22, 83, 4) 
    for ((index, value) in items.withIndex()){ 
    println("the element at $index is $value") 
} 
}

For Loop

fun main(args: Array<String>) { 
    val items = listOf(1, 2, 3, 4) 
    for (i in items) println("values of the array"+i) 
} 

When

fun main(args: Array<String>) { 
    val x:Int=5 
    when (x) { 
    1 -> print("x == 1") 
    2 -> print("x == 2") 
    else -> { // Note the block 
        print("x is neither 1 nor 2") 
    } 
} 
} 

If-Else

fun main(args: Array<String>) {
   val a:Int = 5
   val b:Int = 2
   var max: Int
   if (a > b) {
      max = a
   } else {
      max = b
   }
   print("Maximum of a or b is " +max)
 
   // As expression 
   // val max = if (a > b) a else b
}

Ranges

fun main(args: Array<String>) { 
    val i:Int =2 
    for (j in 1..4)  
    print(j) // prints "1234" 
    if (i in 1..10) { // equivalent of 1 <= i && i <= 10 
    println("we found your number --"+i) 
}  
} 

Map Set

fun main(args: Array<String>) { 
    val items = listOf(1, 2, 3, 4) 
    println("First Element of our list----"+items.first()) 
    println("First Element of our list----"+items.last()) 
    println("Even Numbers of our List----"+items.filter { it % 2 == 0 })   // returns [2, 4] 
    val readWriteMap = hashMapOf("foo" to 1, "bar" to 2) 
    println(readWriteMap["foo"])  // prints "1" 
    val strings = hashSetOf("a", "b", "c", "c") 
    println("My Set Values are"+strings) 
} 

Data Types

fun main(args: Array<String>) { 
    val a: Int = 10000 
    val d: Double = 100.00 
    val f: Float = 100.00f 
    val l: Long = 1000000004 
    val s: Short = 10 
    val b: Byte = 1 
    println("Your Int Value is "+a); 
    println("Your Double  Value is "+d); 
    println("Your Float Value is "+f); 
    println("Your Long Value is "+l); 
    println("Your Short Value is "+s); 
    println("Your Byte Value is "+b); 
  } 

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.