Kotlin: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 99: Line 99:


// Output is 1234we found your number  
// Output is 1234we found your number  
</syntaxhighlight>
=Flow Control=
==If==
if can be used as expression and statements.
<syntaxhighlight lang="kotlin">
if(q.Answer == q.CorrectAnswer) {
// Do something
}
else
{
// Do something else
}
// Or we can do
var message = if(q.Answer == q.CorrectAnswer) {
  "You were correct"
} else {
  "Try again"
}
</syntaxhighlight>
==When==
When can be used like a switch statement.
<syntaxhighlight lang="kotlin">
when(number) {
    0 -> println("Invalid number")
    1, 2 -> println("Number too low")
    3 -> println("Number correct")
    4 -> println("Number too high, but acceptable")
    else -> println("Number too high")
}
</syntaxhighlight>
But it can also be used like an expression too.
<syntaxhighlight lang="kotlin">
var result = when(number) {
    0 -> "Invalid number"
    1, 2 -> "Number too low"
    3 -> "Number correct"
    4 -> "Number too high, but acceptable"
    else -> "Number too high"
}
// it prints when returned "Number too low"
println("when returned \"$result\"")
</syntaxhighlight>
</syntaxhighlight>



Revision as of 05:50, 22 August 2020

Introduction

Kotlin is like java

  • JVM language
  • Object orientated
  • Functional language, high order functions, we can
  • store, pass and return functions
fun main(args: Array<String>) {
    println("Hello World")
}

Types

The following data type are available.

  • Numbers
  • Characters
  • Boolean
  • Strings
  • Arrays
  • Collections
  • Ranges

Numbers

The following Number type are available

  • Byte Size 8, min -128, max 127
  • Short Size 16, min -32768, max 32767
  • int Size 32, min -2,147,483,648 max 2,147,483,647
  • Long Size 64, min -9,223,372,036,854,775,808, max 9,223,372,036,854,775,807
val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1

For Floating Point Numbers

  • Float Size 32, Significant bit 24, Exponent Bits 8, Decimal Digits 6-7
  • Double Size 64, Significant bit 53, Exponent Bits 11, Decimal Digits 15-16
val pi = 3.14 // Double
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float, actual value is 2.7182817

Characters

Kotlin represents character using char. Character should be declared in a single quote like ‘c’. Please enter the following code in our coding ground and see how Kotlin interprets the character variable. Character variable cannot be declared like number variables. Kotlin variable can be declared in two ways - one using “var” and another using “val”.

fun main(args: Array<String>) {
   val letter: Char    // defining a variable 
   letter = 'A'        // Assigning a value to it 
   println("$letter")
}

Boolean

Two values true or false. (See Oracle for why two values was mentioned)

Strings

Strings are character arrays. Like Java, they are immutable in nature. We have two kinds of string available in Kotlin - one is called raw String and another is called escaped String. In the following example, we will make use of these strings.

fun main(args: Array<String>) {
   var rawString :String  = "I am Raw String!"
   val escapedString : String  = "I am escaped String!\n"
   
   println("Hello!"+escapedString)
   println("Hey!!"+rawString)   
}

Arrays

Arrays in Kotlin are represented by the Array class, that has get and set functions (that turn into [] by operator overloading conventions), and size property, along with a few other useful member functions:

class Array<T> private constructor() {
    val size: Int
    operator fun get(index: Int): T
    operator fun set(index: Int, value: T): Unit

    operator fun iterator(): Iterator<T>
    // ...
}

To create an array, we can use a library function arrayOf() and pass the item values to it, so that arrayOf(1, 2, 3) creates an array [1, 2, 3]. Alternatively, the arrayOfNulls() library function can be used to create an array of a given size filled with null elements.

fun main(args: Array<String>) {
   val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
   println("Hey!! I am array Example"+numbers[2])
}

Collections

Ranges

Ranges is another unique characteristic of Kotlin. Like Haskell, it provides an operator that helps you iterate through a range. Internally, it is implemented using rangeTo() and its operator form is (..).

In the following example, we will see how Kotlin interprets this range operator.

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)
   }
}

// Output is 1234we found your number

Flow Control

If

if can be used as expression and statements.

if(q.Answer == q.CorrectAnswer) {
 // Do something
}
else
{
 // Do something else
}

// Or we can do 
var message = if(q.Answer == q.CorrectAnswer) {
   "You were correct"
} else {
   "Try again"
}

When

When can be used like a switch statement.

when(number) {
    0 -> println("Invalid number")
    1, 2 -> println("Number too low")
    3 -> println("Number correct")
    4 -> println("Number too high, but acceptable")
    else -> println("Number too high")
}

But it can also be used like an expression too.

var result = when(number) {
    0 -> "Invalid number"
    1, 2 -> "Number too low"
    3 -> "Number correct"
    4 -> "Number too high, but acceptable"
    else -> "Number too high"
}
// it prints when returned "Number too low"
println("when returned \"$result\"")

Classes

General

class Person() {
    var Name: String = ""

    fun display() {
        println("Display :$Name"
    }
}

Constuctors

If you pass a var to a constructor the name is then associated with the class without declaring the value separately

class Person(var Name: String) {

    fun display() {
        println("Display :$Name"
    }
}

Class Functions

Kotlin supports lambda functions

class Person(var Name: String) {

    fun display() {
        println("Display :$Name"
    }
  
    fun displayWithLambda(func: (s:String) -> Unit) {
        func(Name)
    }
}


Data Class

data class SportsActivity (
       val totalAveragePaceInMinutesPerKilometre: Double,
       val totalAverageSpeedInKilometresPerHour: Double,
       val totalDurationInSeconds: Int,
       val totalAverageDistanceInMetres: Double, 
       var dateOfActivity: Date
)

Reading and Writing to Gson

Given the following

    var mySportsActivity = SportsActivity(
           0.0,
           0.0,
           0,
           0.0,
           Date())
   val gson = Gson()
   val json = gson.toJson(mySportsActivity)
   var filename = "D:\\IAIN\\Output.json";

You can write to a file with

    FileWriter(filename).use {
       writer ->
       val gson = GsonBuilder().setPrettyPrinting().create()
       gson.toJson(mySportsActivity, writer)
    }

And read it back with

    FileReader("D:\\IAIN\\Output.json").use {
       reader ->
       val gson = GsonBuilder().setPrettyPrinting().create()
       mySportsActivity2 = gson.fromJson(reader,SportsActivity::class.java)
    }

Range For Loop

val myTest = 212
for(i in 0..7)
{
  val myGetValue = IsByteSet(myTest,i)
  val myTest2 = myGetValue
}
Reversed is a bit rubbish but here it is
val myTest = 212
for(i in 7 downTo 0)
{
  val myGetValue = IsByteSet(myTest,i)
  val myTest2 = myGetValue
}