Friday, April 10, 2020

Kotlin - Classes and Objects

Classes and Objects

Basically, classes are templates that allow you to create your own types of objects and define their properties and functions.

object types are defined using classes. for example:

 var x = 6

this creates an Int object with a value of 6.
When you create an Int object. the compiler checks the Int class and sees that it requires an integer value and has functions such as toLong and toString.

You can define your own class


  1. The things each object knows about itself.
  2. The things each object can do.

The things an object knows about itself are its properties. They represent an object state(the data) and each object of that type can have unique values.

For example:

class Dog(val name: String, var weight :Int ,val breed:String)
{
   fun bark()
   {
       println(if (weight < 20) "Yip" else "woof")
   }
}

A function that's defined inside a class is called a member function. Its sometimes called a method. This is just like the functions only difference is that it's defined inside the class body.

Now let's create object:

var myDog = Dog("Name",70 ,"Mixed")

How to access properties and functions

var myDog = Dog("Name",70 ,"Mixed")
pritln(myDog.name)  

It's like saying go to myDog and get its name.
you can also use the dot operator to call an object's function.

var myDog = Dog("Name",70 ,"Mixed")
pritln(myDog.name)  
myDog.bark()

It's like go to myDog and call its bark function.

What if the Dog is in a Dog Array?

var dogs = arrayOf(Dog("FirstDog",50,"Mixed"),Dog("SecDog",50,"Mixed"),Dog("ThirdDog",50,"Mixed"))

This code creates three Dog objects and them to an array<Dog> array named dog. You can still access the properties and functions of each dog in the array-like

dogs[0].weight = 15
dogs[1].bark()

The compiler knows that dogs[] is a Dog object so you can access the Dog properties and call its functions.

A constructor runs when you instantiate an object. It is used to define properties and initialized them. The above example shown is called the primary constructor.

The Dog constructor defines properties and each property is really just a variable that's local to the object. A value is then assigned to that variable.

An object is sometimes known as an instance of a particular class so its properties are sometimes called instance variables.

So here you can ask a few questions:

Does the constructor allocate the memory for the object that's being created?
Ans: No the system does.  The constructor initializes the object so it makes sure that the object properties are created and that they are assigned their initial values. All memory is managed by the system.

Can I define a class without defining a constructor?
Ans: Yes you can.

In java, you don't have to initialize the variables that you declare inside a class.is there a way of not initializing class properties in Kotlin?
Ans: If you are completely certain that you cant assign an initial value to the property when you call the class constructor .you can prefix it with lateinit.This tells the compiler that you are aware that the properties have not been initialized yet, and you will handle it later. If you want to mark the temperament property for late  initialization for example:

lateinit var temperament: String 

Doing this will allows the compiler to compile your code.

What happens if I try to use a property value before it's been initialized?
Ans: if you do not initialize a property before you try and use it.you will get a runtime error when you run the code.

Can I use lateinit with any type of property?
Ans: you can only use lateinit with properties defined using var and you can use it with any of the following types Byte ,Shot, Int,Long, Double, Float,Char or Boolean. This means that properties of any of these types must be initialized when the property is defined or in an initializer block.

Small Example;

class TapeDeck
{
   var hasRecoder = false
 
    fun playTape()
   {
         println("Tape is playing")
   }

   fun recordTape()
   {
         println("Tape is recording")
   }
}

fun main(args:Array<String>)
{
   t.hasRecoder = true
   t.playTape()
   t.recordTape()
}

let's take big code understand the class and objects:

class Dog(val name : String , weight_param :Int,breed_param:String) // primary constructor
{
   init{
      print("Dog $name has been created") // init block
   }

    var activities = arrayOf("Walks")
    val breed = breed_param.toUpperCase()
    init
   {
      println("The breed is $breed")
   }

   var weight = weight_param
         set(value){
             if(value > 0)  field = value
        }

   val weightInkgs : Double
          get() = weight / 2.2

    fun bark()
    {
        println( if(weight < 20 ) "Yip" else "woof")
    }
}

fun main(args: Array<String>)
{
   val myDog = Dog("Dog1", 80 , "Mixed")
   myDog.bark()
 
    myDog.weight = 75
    println("Weight in Kgs is ${myDog.weight}")

   myDog.activities = arrayOf("Walks","Fetchig balls',"Frisbee")
   for(item in myDog.activities)
    {
       println("My dog enjoyed $item")
     }

}

Bullet Points:

  1. Classes let you define your own types
  2. A class is a template for an object. One class can create many objects.
  3. A property is a variable that's local to the class.
  4. The class keyword defines a class
  5. A constructor runs when you initialize an object.
  6. You can define a property in the primary constructor by prefixing a parameter with all or var. you can define a property outside the constructor by adding it to the class body.
  7. Initialized blocks run when an object is initialized. 
  8. Behind the scenes, the compiler adds a default getter and setter to every property.


















Sunday, April 5, 2020

Kotlin - Functions Concept

Functions:

So far we have seen the main function. So if you want to split your code into separate functions. So main function is actually launched your application as it the function that gets executed when you run it.So how to create a function.

For example;

fun test()
{
  println("Test")
}

So once you have written the function you can call it from elsewhere in your application:

fun main(args: Arrays<String>)
{
 test()
}

you can also send things to a function.you can tell the compiler what values a function can accept by your specification one or more parameters you can pass:

fun test(param: Int)
{
  println("Paramater is $param")
}

// you can call it like

test(6)

You can also pass variables to a function so long as the variable type matches the parameter type:

fun main(args: Array<Strings>)
{
  val x: Int =7
  val y:Int =8

  printSum(x,y)
}

fun printSum(int1: Int, int2:Int)
{
   val result = int1 + int2
   println(result)
}

You can also get things back from a function:

So if you want to get something back from a function.you need to declare it.for example:

fun max(a: Int, b:Int) : Int   // this tells the compiler that the function returns an Int value
{
   val maxValue = if(a > b) a else b
  return maxValue;  // you can not return string here you have to return Int only
}

Functions with no return value:

if you do not want to return a value you can either omit the return type from the function declaration or specify a return type Unit. Declaring ta return type Unit means that the function returns no value as in the example:

fun printSum(int1 : Int , int : Int2)
{
  val result = int1 + int2
   println(result)
}

or

fun printSum(int1 : Int, int2 : Int): Unit
{
  val result = int 1 + int 2
    println(result)
}

But if you try to return a value in function with no declared return type or a return type of Unit, your code won't compile.

Functions with single-expression bodies:

if you have a function whose body consists of a single expression. you can simplify the code by removing the curly braces and return statement from the function declaration. for example:

fun max(a: Int,b:Int) : Int
{
  val maxValue = if(a > b) a else b
  return maxValue
}

The function returns the result of a single expression which means that we can rewrite the function like below:

fun max(a:Int , b:Int):Int = if (a > b ) a else b

// here we have used = to say what the function returns and remove the {}'s

because the compiler can infer the function return type from the if expression we can make the code even shorter by omitting the : Int

fun max(a:Int,b:Int) = if (a > b) a else b

 here the compiler knows that a and b are Ints So it can work out of the function return type from the expression

So you can ask more questions here like :

  1. Can I return more than one value from a function?. A function can declare only one return value but if you want to say return three Int values then the declared type can be an array of Ints(Array<Int>). Put those Ints into the array and pass it back.
  2. Do I have to do something with the return value of a function? Can I just ignore it? Kotlin does not require you to acknowledge a return value. you might want to call a function with a return type even though you do not care about the return value.in this case, you are calling the function for the work it does inside the function rather than for what it returns. you do not have to assign or use the return value.
Example:

fun main(args: Array<Strings>)
{
  val options = arrayOf("One","Two","three")
  val gameChoice = getGameChoice(options)
 val userChoice = getUserChoice(options)
  pritnResult(userChoice,ganeChoice)
}

fun getGameChoice(optionsParam:Array<String>) = optionsParam[Math.random() * optionsParam.size).toInt()]

fun getUserChoice(optionParams:Array<String>) : String
{
   var isValidChoice = false
   var userChoice = ""
   while(!isValidChoice)
  {
     print("Please enter one of the following:")
     for(item in optionParams) print(" $item")

     val userInput = readLine()
     if(userInput!=null  && userInput in optionParam)
    {
       isValidChoice = true
        userChoice = userInput
    }

    if(!isvalidChoice) println("you must enter a valid choice.")
  }
  return userChoice
}

fun printresult()
{
  val result  : String
  if(userChoice == ganeChoice) result = "Anything you would like to print"
  else if((userChoice == "One" && userChoice == "Two" && userChoice == "Three")
  {
    print("print something here")
  }
  else result = "You wnated"
println("You chose $ userChoice . I chose $gameChoice . $result ")
}


Bullet Points to remember:


  • use function to organize your code and make it more reusable.
  • A function can have parameters so that you can pass more than one value to it
  • The number and type of values you pass to function must match the order and type of the parameters declared by the function.
  • A function can return a value. you must define the type of value it returns
  • A Unit return type means that the function does not return anything.
  • Choose for loops over while loops when you know how many times you want to repeat the loop code.
  • The ReadLine() function reads a line of input from the standard input system.it returns a String value, the text entered by the user.
  • If the input system has been redirected to a file and the end of the line has been reached, the readLine() function returns null, null means it has no value or its missing.
  • && means "and". || means "or" . !means "not".











Kotlin - Basic Types and Variables

Basic Types and Variables

Here I wills how you how Kotlin variables really work. So you will know about Kotlin's basic types such as Ints, Floats, and Booleans. I will also tell how to create arrays to hold multiple values and Finally you will discover why Objects are so important in Kotlin.

Your code needs a variable like

var x =5

So what is behind the scene ?.

So variables are like cup right. it can be small, Big based on our requirements but it will have one thing in common that it will hold the value.

So here if you say like x = 5 that means

1)What the variable name is.
2)whether or not the viable can be reused.
3)What type of variable it is.

You have to tell these things to the compiler.

So our compiler cares about the type of our variables. For this type safety to work, the compiler needs to know.

Let see how this works:

when you declare a variable using code like:

var x = 5 

the value you are assigning to the variable is used to create a new object And the compiler infers the variable's type from the object. So the compiler knows that you need a variable with a type of int so that it matches the type of object.

The variable holds a reference to the object when an object is assigned to a variable, the object itself doesn't go into the variable. A reference to the object goes into the variable instead.

val vs. var 

if you declare the variable using val, the reference to the object stays in the variable forever and can not be replaced but if you use the var keyword instead you can assign another value to the variable.

var x = 5
x = 6

So we can replace the reference held by the variable because its been declared using var but at the same time, it would not be possible if it declared the variable using val.

Bullet Points:


  • In java numbers are primitives so a variable holds the actual number. Is that not the case with Kotlin? No, it is not the case with Kotlin because in  Kotlin , numbers are objects and the variables hold a reference to the object, not the object itself.
  • Why does kotlin care so much about the variable's type? Because it makes your code safer and less prone to error.
  • In java, you can treat Char primitives as numbers. Can you do the same for Chars in kotlin.No Chars in Kotlin are characters not he numbers.
Some Examples:

fun main(args: Arrays<String>)
{
   var x : Int = 65.2  // this is not valid Int value
   var isPunk = true
   var message = 'Hellow'   // Single quotes are used to define Chars which holds single charecters.

    var y =7
    var bigNum: Long = y.toLong()
    var b: Byte = 2
  
 }

Now we see how to create an Array:

you can create an array using the arrayOf() function. for example:

fun main(args: Array<String>)
{
   val wordArray = arrayOf("24/7","Multi-Tier","B-To-B")
   var arraySize = wordArray.size
   
   val rand = (Math.random * arraySize).toInt  // This generates a random number returns a random number between 0 and 1 .We sue use Int() to force the result to be an integer.

   val phrase = "${wordArray[rand]}"
   println(phrase)
}

Note: Arrays hold items of a specific type.you can either let the compiler infer the type from the array's values or explicitly define the type using Array<Type>.

var vs val concept in Array :

So we need to understand the effect val and var have when you declare an array.
As you know a variable holds a reference to an object. when you declare a variable using var you can update the variable so that it holds a reference to a different instead.
If the variable holds a reference to an array this means that you can update the variable so that if it refers to a different array of the same type. for example:

var myArray = arrayOf(1,2,3)
myArray = arrayOf(4,5)

So let's understand what happens:

var myArray = arrayOf(1,2,3) This creates an array of Ints and a variable names myArray that holds a reference to it.

myArray = arrayOf(4,5) This creates a new array of Ints. A reference to the new array gets put into the myArray variable, replacing the previous references.

So what happens if we use the variable val instead?

val means the variable points to the same array forever. when you declare an array using val.you no longer update the variable so that it holds a reference to a different array. for example:

val myArray = arrayOf(1,2,3)
my Array = (4,5,6)

Once the viable is assigned an array. it holds a reference to that array forever but even though the variable maintains to the same array. the array itself update the variables in the array.

But there is catch you can still update the variables in the array.

Declaring a variable using val means that you can not reuse the variable for another object.you can however still update the object itself.

for example:

val myArray = arrayOf(1,2,3)
mayArray[2] = 6    // This updates the 3rd item in the array

Bullet Points:

  1. If the variable type is not explicitly defined the compiler infers it from its value.
  2. A variable holds a reference to an object
  3. An object has state and behavior. its behavior is exposed through its functions.
  4. Kotlin has a number of basics types: Byte,Short,Int,Long,Float,Double,boolean,Char and String.
  5. You can only assign a value to a variable that has a compatible type.
  6. If you define an array using val. you can still update the items in the array.
















Kotlin Concepts and Programming

Kotlin is making waves. The question is why?

Kotlin is syntax friendly, conciseness, flexibility and powerful language. The compiler keeps you safe like unsafe, buggy code and kotline's compiler puts a lot of effort into making sure your code is as clean as possible, preventing many of the errors that can occur in other programming languages.

So Kotlin virtually eliminates the kind of error that regularly occurs in other programming languages that means safer, more reliable code and less time spent chasing bugs.

You can use Kotlin nearly everywhere

This is because you can choose which platform to compile your Kotlin code against.

Java Virtual machines(JVMs)
it can be compiled to JVM bytecode so you can use Kotlin practically anywhere. Kotlin is 100% interoperable with java.

Android
Kotlin has first-class support for Android.

Client-side and server-side JavaScript

you can also transpile -----or translate and compile ---- Kotlin code into JavaScript.So you can run it in a browser. You can use it to work with both client-side and server-side technology such as WebGL or Node.Js

Native Apps
You can also directly compile your kotlin code to native machine code. This allows you to write code that will run for example on iOS or Linux.

Now take a look on few examples:

val name = "Abhinav"  // Declare a variable 'name' and give it a value of "Abhinav"

val height = 9

println("Hellow")

val a = 6
val b = 7

val c = a + b+10
val str = c.toString()

val numList = arrayOf(1,2,3,4,5,6,7)

var x = 0

while(x < 3)
{
   println("Item $x is ${numList[x]}")
   x = x + 1
}

Sample Program: 

App.kt:

fun main(args : Array<String>)
{
  println("ABHINAW")
}

So you can ask a question here like

Do I have to add the main function to every Kotlin file I create?
Ans: No, A kotlin application might use dozens of files but you may only have one with the main function - the one that starts the application.

Now let's run the  above code here:

So when you run the code in IDE :

1) The IDE compiles your kotlin code source code into JVM bytecode.
that means compiling App.kt creates a class file called AppKt.class .

2)The IDE starts the JVM and runs AppKt.class
The JVM translates the Appkt.class bytecode into something the underlying platform understands then runs it.

Bullet Points:


  • Use fun to define a function.
  • Every application needs a function named main.
  • Use // to do single-line comment.
  • A string is a string of characters. You denote a String by closing its characters in double-quotes.
  • Code blocks are defined by a pair of curly braces {}.
  • The assignment operator is one equals ==.
  • The equals operator use two equals signs ==.
  • Use var to define a variable whose value may change.
  • Use all tod define a value whose value will stay the same.
  • you can also use if as an expression so that it returns a value.In this case , he else clause is mandatory.