Pages

Monday, June 18, 2018

Learn Kotlin 12 (Generics)

Generics

Kotlin provides higher order of variable typing called generics. As in java classes in kotlin may have type parameters .The idea is to allow type (Integer, String,.....etc and user defined types ) to be a parameter . like it would be nice to write a method which could work on the elements in an integer array a string array or an array of any type

class Id(t:T){
var value = t
}
//to create an instance we need to provide the type argument
val id : Id<Int> = Id<Int> (1)
But if the parameters may be infered eg from the constructor argument or by some other means one is allowed to omit the type arguments
val id = Id(1)
//1 has type int so the compiler
//figures out that we are talking about Id<Int>
In other languages like java has a type system is wildcard types and in kotlin doesn't have any instead it has two other things called as declaration-sits and type projections 
Declaration-site variance
suppose we have generic interface Source<T> that does not have any methods that takes T as a parameter ,only methods that return T . in kotlin there are two key words in and out if we can annotate the type parameter T of Source to make sure it only returned(produced)from members of Source<T> and never consumed means that the produced means you can only read from statement
and cannot write
interface Source<out T>{
fun nextT():T
}
fun demo (strs:Source<String>){
val objects:Source<Any> = strs
//this is okay since T is an out parameter
}
The general rule is when a type parameter T of a class C is declaraed out it may occur only in out-position in the members of C but in return C<Base> can safely be a supertype of C<Derived>
in clever words they say that the class C is covariant in the parameter T or that T is a covariant type parameter think C as being producer of T's and NOT a consumer of T's

The out modifier is called a variance annotation and since it is provided at the type parameter declaration site we talk about declaration site variance
The other key word is in it makes a type parameter contravariant it can only be consumed and never produced as example :

interface Comparable <in t>{
operator fun compareTo(other: T):Int
}
fun demo (x:Comparable<Number>){
x.compareTo(1.0)
//1.0 has type Double which is a subtype of Number
//thus we can assign x to a variable of type comparable<Double>
val y:Comparable<Double> = x//OK!
 }

Type projection

Use-site variance:Type projections

It some cases some classes can't actually be restricted to only return T's A good example of this Array

class Array (val size:Int){ 
fun get (index : Int):T{/*....*/} 
fun set(index: Int,value:T){/*....*/}
}
This class cannot be either co-or contravariant in T And this imposes certain inflexibilities here is an example
fun copy(from:Array<Any>,to:Array<Any> ){
assert (from.size == to.size)
for (i in from.indices)
to[i] = from [i]
}
This function is supposed to copy items from one array to another Lets try to apply it in practice:

val ints: Array<Int> = arrayOf(1,2,3)
val any = Array<Any>(3){ "" }
copy (ints,any)
//Error : expects (Array <Any>,Array<Any>)

Here Array <T> is invariant in T thus neither of Array <Int> and Array<Any> is a subtype of the other  because copy might be doing bad things it might attempt to write say a String to from and if we actually passed an array of Int there a ClassCastException would have been thrown sometime later
so we make sure that copy doesn't do any bad things like we need to prevent it from writing and we can :

fun copy (from:Array<out Any>,to:Array<Any>){
//......
}


What has happened here is called type projection the from is not simply an array but restricted (projected) one: we can only call those methods that return the type parameter T In this case it means that we can only call get() .this is our approach to use site variance
you can also project a type with in as well

That's all for this post friends hope you like it to get latest updates on lessons please followby email and don't forget to share follow and comment on this post



Saturday, June 16, 2018

Learn Kotlin 11 (Object declaration,properties and fields )

Object Declaration

We have heard about Singleton . which is useful in situations like creating facade objects and kotlin makes it easy declare singleton as here
object HomeManager{
fun registerHomeProvider(provider:HomeProvider){
//....
}
val allHomeProviders:Collection<HomeProvider>
get() = //.....
}
This is called an object declaration and it always has a name following the object keyword just like variable declaration  an object declaration is not an expression and cannot be used on the right hand side of an assignment statement object declarations initialization is thread safe to refer to an object we use its name directly like given below
HomeManager.registerHomeProvider{.....}
Such objects can have supertypes to like given below as
object DefaultListener:MouseAdapter(){
 override  fun mouseClicked (e:MouseEvent){
 //......
}
 override fun mouseEntered(e:MouseEvent){}{
//........
}
}
The points to remember here are that object declaration can't be local (be nested directly inside the function ) they can also be nested into other object declarations or non inner classes

Companion Objects

And in kotlin like in other languages classes do not have static methods in most cases its recommended to simply use package level function instead
And if you need to write function that can be called without having class instance but needs access to the internals of a class for example a factory method you can write it as a member of an object declaration inside class as defined above
and more specifically if you declare a companion object inside your class you can call its members as same as static methods in java /C# like given below

class NadsClass {
companion object Factory{
 fun create():NadsClass = NadsClass()
}
  }
Members of the companion object can be called by using simply the class name as the qualifier as given below
val instance = NadsClass.create()
As the members of companion objects look like static members in other languages ,Those are still instance members of real objects and can for example implement interfaces  and one thing to remember here is that the name of the companion object can be ignored in which the name Companion will be used as for example
interface Factory <T>{
fun create():T
}
class NadsClass{
companion object : Factory<NadsClass>{
override fun create (): NadsClass = NadsClass()

}


There is a way in which on JVM you can have members of companion objects generated as real static methods and fields if you use the @JvmStatic annotation to get more details see java interoperability

Properties and fields

Backing Fields
The backing field cannot be declared  directly in kotlin classes when a property needs a backing field kotlin provides it automatically this backing fields are referenced in the accessors using the field identifier
 
var count = 0
//remember the initializer assigns the backing field directly
set(value){
if (value >=0) field = value
}
The field identifier can only be used in the accessors of the property and the backing fields are generated for a property if it uses the default implementation of at least one of the accessors or if a custom accessor references it through the field identifier
here is an example with no backing field

val isEmpty :Boolean
get() = this.size == 0

Backing property 

To do something that does not fit into this implicit backing field scheme you can always fall back to having a backing property as :
 
private var _table: Map<String,Int>? = null
public val table : Map <String,Int>
get(){
if(_table == null ){
//Type parameter are infered
__table == HashMap()
}
return __table ?: throw AssertionError ("set to null by another thread")
}

This is just the same as in java since access to private properties with default getters and setters is optimized so that no function call overhead is introduced


Thats all for this post guys hope you like this post comment your suggestions and doubts in the comment section and don't forget to share and follow and to get latest lessons and updates on this blog follow by email id 

Sunday, June 10, 2018

Learn Kotlin 10 (CLASSES: hi friends this is the continuation of previous post so i kindly request you to read from the first chapter and if you are a beginner its easy to learn just read through and understand it and dont need to by heart it )

Abstract Class

A class and its members can be declared as abstract which means an abstract member does not have an implementation in its class an abstract class is open there is no need annotate it with open we can also override non abstract open member with abstract one
open class Base{
open fun f(){}
}
abstract class Derived :Base(){
 override abstract fun f(){
}
}

Interface

This is certain type of classes which contains declaration of  abstract methods as well as method implementation of the difference between abstract class and interface is that interface cannot store state interface can have properties but they need to be abstract or to provide accessor implementation
an interface is defined using "interface" keyword .A class or object can implement one or more interfaces we can declare properties in interface a property declared may be abstract or it can provide implementation for accessors
interface Firstinterface{
var age:Int //abstract
var withimplementation:String
get() = "twothousand" 
fun mufun(){}
}
interface Secondinterface{
fun sufun(){}
}
class Myclass : Firstinterface,Secondinterface{
//implementing two interfaces

override fun mufun(){
//body
}
override fun sufun(){
//body
}
}

Visibility modifiers

The classes , objects, constructors ,interfaces ,functions,properties, and their setters can have visibility modifiers getters always have the same visibility as their property the visibility modifiers are
packages  :packages are files declared with package keyword and it can contain declaration of classes functions or interfaces functions, properties and classes ,objects and interfaces  can be declared on the top-level directly inside the package
note : local variables ,functions,classes cannot have visibility modifiers
  • private: if we mark a declaration private it will only be visible inside the file containing the declaration as if it is inside the class then it will be visible inside the class only
  • protected: protected is not available for top-level declaration but inside the class it is same as private but visible to the subclasses too if you override a protected member and do not specify the visibility explicitly the overriding member will also have protected visibility
  • internal: the internal classes are which if you mark declaration as internal it is visible everywhere inside the module and if it is in the class any client inside this module who sees the declaring class sees its internal members (module in kotlin a module is a set of kotlin files compiled together like : an intelIj IDEA module, a maven project)
  • public: by default the declarations are marked public means your declaration will be visible every where in class any client who sees the declaring class sees its public members
note: to use a visible top-level declaration from another package you should still import it 
//file name is nadeem.kt
package nads

private fun foo(){} //visible inside nadeem.kt only
public var bar:Int = 5 //property is visible every where
private set //setter is only visible inside nadeem.kt
internal val baz = 101 //visible inside the same module

 Object Expressions and Declaration

To modify a class with out explicitly declaring a new subclass for it we use the object expression and object declaration
object expression
to create an object of anonymous class that inherits from sometype we write

 window .addmouselistener(object: MouseAdapter(){
override fun mouseclicked(e:MouseEvent){
}
override fun mouseEntered(e:MouseEvent){

}
})
If a supertype has a constructor appropriate constructor parameter must be passed to it many supertype may be specified as a comma separated list after the colon we can also create an object with no nontrivial supertype  

open class First(){
 public open val y:Int = x
}
Interface Second{....}
val ab:First = object : First(1),Second{
override val y = 15
}
//an object with no nontrivial supertype
fun foo (){
val adhoc = object {
var x :Int = 0
var y : Int =0
}
 print(adhoc.x + adhoc.y)
}

One thing to note here is that anonymous objects can be used as types only in private and local declarations if you use an anonymous object of a return type by using anonymous object as the return type of public function or the type of public property  the actual type of that function or property will be declared as the supertype of the anonymous object or "Any".if you didn't declare any supertype members added in the anonymous object will not be accessible
class mised(){
//private function so the return type is anonymous object type
private fun mis = object{
val s :String = "s"
}
//public fun so the return type is Any
 fun foo ()  = object{
val s : String = "s"
}
fun bar(){
val s1 = mis().s //works
val s2  = foo().s//shows error
}
}
Code in the object expressions can access variables from the enclosing scope and this is not restricted to final variables
fun changename(window:JComponent){
var name1 = "vas"
var name2 = "vas2"
window.addMouseListener(object: MouseAdapter(){
override fun mouseClicked (e:MouseEvent){
name1 = "nak"}
override fun mouseEntered(e:MouseEvent){
name2 = "vak"
}})}

Thanks guys hope you like the post more will be included on the next post to get latest posts please follow by email and follow me and don't forget to share and comment below your suggestions and doubts

Wednesday, June 6, 2018

Learn Kotlin 9 (Classes and Inheritance3:Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

Overriding Methods

Here is an example of overriding methods
open class Base{
          open fun my(){}
          fun my2(){}
}
class Derived: Base {
 override fun my(){
//overrid here
}
}
The override annotation is required here for Derived.my and if it were missing the compiler will complain andif there is no open annotation on functions like Base.my2 then declaring a method with same signature in a subclass is illegal either with override or without it in a final class open members are prohibited a memeber marked override is itself open it may be overriden in subclasses to prohibit overriding you can use the final keyword

Properties

The properties are variables which have a class level scope and which are declared inside the class but outside the methods or functions is called as a property in kotlin these can be declared as mutable using var keyword and immutable with val keyword
class Home{
 var owner:String="alex".
var name:String="mannat"
var lane:String="pk lane"
var address:String= "is address"
}
To use a property we simply refer to it by name
fun copydetails(home:Home):Home{
val details = Home()
details.name = home.name//accessors are called to access the values
details . owner = home.owner
return details
}

Getters And Setters

The getters and setters are methods on which the getter method is used to which returns the value and setter method which sets the value for the method. a full syntax a property is declared as is
var <property name>[:<propertytype>][= <property_initializer>]
[<getter>]
[<setter>]
here the getter and setter are optional and property type is also optional if the type can be infered from the initializer or from the getter return type and for immutable variables with val keyword the setter method is not allowed
here is some examples for default getters and setters for mutable and immutable variables
var age:Int?
//error as the explicit initializer is required, default getter and setter implied
var initialize = 1//has type int default getter and setter
val ages : Int? //has type int and default getter
 

we can write custom accessors like ordinary functions inside the property declarations here is an example of a custom getter
val isEmpty: Boolean
     get() = this.size == 0
   
A custom setter looks like this
var name:String
get.this.toString()
set(value){
setDataFromString(value)
//parses the string and assigns value to other properties
}
By convention the name of the setter parameter is value but we can chose a different one if we need
and you can ignore the property type if it can be inferred from the getter if we need to change the visibility of accessor or annotate it but don't need to change the default implementation we define the accessor without defining its body like
var isEmpty get() = this.size == 0//by getter we know its type boolean
var settervisibility:String = "abc"
private set
//the setter is private and have default implementation
var setterwithannotation:Any? = null
@Inject set //annotate the setter with inject

Overriding properties

The overriding properties works similar to overriding methods were properties declared on a superclass are then redeclared on the subclass must be prefaced with override and they must have a compatible type each declared properties can be overriden by a property with an initializer or by a property with a getter method for example
open class Foo{
       open val numb:Int get(){}
}
class Bar1:Foo(){
      override val numb :Int =...
}
A val property can be overrided with a var property because the val property always declares a getter method and overriding it as a var additionally declares a setter method in the derived class ()
we can use a override keyword as part of the property declaration in a primary constructor

Interface Foo {
val count :Int
}
class Bar1(override val count: Int):Foo
class Bar2:Foo{
override var count:Int = 0
}

Derrived class Initialization Model

A point to note here is construction of new instance of a derived class the first step done is the initialization of the base class (preceded only by evaluation of the arguments for  the base class constructor ) and thus happens before the initialization logic of the derived class is run

Calling Super Class

The super class is the base class of the derived class the code in derived class can call its superclass function and property accessors implementation using the super keyword

Overriding rules

If a class inherits from many implementations of the same member from its immediate superclasses it must override this member and provide its own implementation (using one of the inherited ones ).to denote the supertype from which the inherited implementation is taken we use the super qualified by the supertype name in angle brackets eg:-super<Base>

open class A{
 fun f(){println("A")}
fun a(){println("a")}

}
interface B{
 fun f(){print("B")}//interface will be explained later
fun b(){print("b")}//interface members are open by default
}
class C :A(),B{
//the compiler requires f to be overriden
override fun f(){
super<.A>.f() //call to A.f()
super<B>.f() //call to B.f()
}
}
In here class C is both inherited from both A and B and we have no problem with function a() and b() since C inherits only one implementation of each of this function but for f() we have two implementations inherited by C and thus we have to override f() in C and provide our own implementation that eliminates ambiguity 

Tuesday, June 5, 2018

Learn Kotlin 8 (Classes and Inheritance2:Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

Secondary Constructors

the class can also declare secondary constructor helps to include some extra logic while initializing the primary constructor the secondary constructor are prefixed with constructor keyword here is an example
class Myclass(){
constructor (parent:Myclass){
parent.children.add(this)
}

}
if the class has a primary constructor each secondary constructor needs to delegate to the primary constructor either directly or indirectly through another secondary constructors delegation to another constructor of the same class is done using the this keyword

class Myclass (val name :String){
 constructor (name:String,parent:Myclass ):this(name){
parent.children.add(this)
}
}
here code in the initializer block effectively becomes the part of the primary constructor the delegation to primary constructor happens as in the first statement of the secondary constructor so the code in the all initializer block is executed before the secondary constructor body even if the class has no primary constructor the delegation still happens implicitly and the initializer blocks are still executed

class Constructors {
init(){
println("its the init block")}
 constructor(i : Int){
println("constructor")
}
}
fun main(args: Array<String>) {
    Constructors(1)
}
//this will be the output
its the init block
constructor
if no primary and secondary constructor are not declared in non abstract class (abstract class will be explained later ) it will generate a primary constructor with no arguments the visibility of the constructor will be public (means visible everywhere) if you do not wan't to have a public constructor you need to declare empty primary constructor with non default visibility

class nodefault constructor(){

}
If all of the parameters of primary constructor have default values the compiler will generate an additional parameterless constructor which will use the default values this makes it use kotlin with libraries like jackson or JPA that creates class instance through parameterless constructors


Creating Instance of classes 
To create a instance of a class we call the constructor as if it were a regular function the creation of instance is known as instantiation.the objects are created from classes by subroutines called constructors an object is an instance of a class instantiation is then also known as construction
val myclass = Myclass ()
val myshow = Myshow("joy mathew")
note that like in java kotlin doesn't have new keyword

 Inheritance

Inheritance is which enables the object to take the properties of other object like inheriting from one object this is termed as the inheritance by the child object inherits from the parent object and in kotlin all the classes have a common superclass "Any" this is the default superclass for a class with no supertypes declared. To declare an explicit supertype we place the type after a colon in the class header here is an example :

open class Base (p:Int)
class Derived (p:Int): Base (p)
The open annotation on a class is the opposite of final keyword in java language(the class with final cannot be subclassed) it allows others to inherit from this class. By default all classes in kotlin are final
If the derived class has a primary constructor then the base class can (and must be) initialized there using the parameters of the primary constructor if the class has no primary constructor then each secondary constructor has to initialize the base type using the super keyword or to delegate to another constructor which does that . In this case different secondary constructors can call different constructors of the base type

class Myview : View {
           constructor (ct : Context ): super(ct)
            constructor(ct : Context,attr :Attributeset):super(ct)
}

Overriding Methods

 The overriding a method is a feature in which allows the subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes Kotlin requires explicit annotations for overridable members (we call them open ) and for overrides

Thats all for this post guys the overriding methods will be continued in the next lesson i feel sleepy so hope you like my post if you have any suggestions or doubts feel free to add  it on the comment section and don't forget to share to get latest updates on this lesson follow by email and follow me thanks for your support guys

Monday, June 4, 2018

Learn Kotlin 7 (Control Flow 3 and Classes and Inheritance1:Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

Break and Continue statement

The break statement is used to terminate the nearest enclosing loop the break keyword terminates the controller flow if some condition has failed . before going to examples here is one thing to learn that is label any expression in kotlin may be marked with a label labels have an followed by @ signs for example foo@,myfunc@ etc are valid labels to label an expression we just put a label in front of it here is an example 
loop@ for (i in 1..5){
for (j in 1..3){
if (i ==2) break@loop
}
}
A break qualified with the label jumps to the execution point right after the loop marked with that label
Continue statement is the opposite of the break statement if continue is put here it will proceed to the next iteration of that loop

Classes and Inheritance

A class is a blueprint or prototype from were which objects are created it represents the set of properties or methods that are common to all objects of one type when we are creating a class it's describing  how the object should be made an object may have different instance variable values the objects of the class may have same methods but its behavior may be different simply an object have states and behaviors and an object is the instance of a class
           now we should go somewhat briefly to explain the class with samples so the classes in kotlin are declared using the class keyword

class Myclass {
}
The class name here is Myclass the class declaration consists of the class name the class header (specifying its type parameters the primary constructors etc(type parameter and primary constructor are explained below)) and the class body surrounded by curly braces both the header and body are optional if the class has no body curly braces can be omitted like

class Empty
Now we can see what is a type parameters and the primary constructors
Type parameters
The type parameters are placeholder for a specific type which we will see in the following lessons

Primary Constructors

The constructors are the block of code which are similar to method (methods are like functions inside the class ) thats called when an instance of an object is created and like methods constructor doesn't have return types and the name of constructor must be same as the class name
                A class in kotlin can have a primary constructor and one or more secondary constructor it comes after the class name(optional type parameter)

class Dog constructor(Name : String){

}
if the primary constructor doesn't have any annotations or visibility modifiers we can omit the constructor keyword the primary constructor cannot contain any code initilization code is placed in the initilizer block with init keyword here is an example

class myclass(name: String){
val firstname = "firstname = $name".also (::println)
init{
println ("first initializer block that prints ${name}")
}
val namelength = "namelength = ${name.length}".also(::println)
init{
println ("second initializer block that prints ${name.length}")
}
}
fun main(args: Array<String>) {
    InitOrderDemo("nadeem")
}
//the out put will be as following
firstname = nadeem
first initializer block that prints nadeem
namelength = 6
second initializer block that prints 6

As given above the first constructor second constructor are made and outputs as first initializer and second initializer you can clearly learn from the above code parameters of the primary constructor can be used in the initializer block they can also be used in the initializers declared in the class body
if the constructor has annotations or visibility modifiers the constructor keyword is required and the modifiers go before it
class Customer public @Inject constructor(name: String){
}
The constructor given above have the public which is a visibility modifier (which defines the visibility of this class) and @Inject is the annotation here


Thats all for this post.Hope you like the post follow by email or follow me to get latest updates on this lesson and don't forget to share and comment below your suggestions and doubts thanks guys


Sunday, June 3, 2018

Learn Kotlin 6 (Control flow 2:Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section )

for Loops

for loop iterates through anything that provides an iterator and here is an example then we can explain about the for loop :

for(items in collection) print (item)

here the for loop arguments are a "collection" and "items" the elements in the collection is put on items one by one and printed out in the print statement inside the for loop until collection is over. the body can be a block also like given below as:

for (items:Int in ints){
//the code to be executed here
}
the for loop has a member or extension function which is iterator() whose return type has a next() and hasnext() function which returns boolean all of this three function have to be marked as operators to iterate over a range you can use range expression for example:

for (i in 1..5){
 println(i)
}
for (i in 6 downTo 0 step 2){
println(i)
}
//the output will be as
1
2
3
4
5
6
4
2
0
the first one were i is printed out the value from range 1 to 5 and in the second for loop i is assigned value from 6 to 0 going down so the "downTo" keyword is used and printed out from 6 to 0 with a step of 2 so it out puts 6,4,2,0 with a difference of 2
A for loop over a range or an array is compiled to an index based loop that does not create an iterator object here is
var array = arrayOf("a","b","c")
for(i in array.indices){
println(array[i])
}
//the output will be as
a
b
c

In here we can see that the array indices are put on the i and printed out as array[i] now there is other one that is
var array = arrayOf("a","b","c")
for ((index,value) in array.withIndex()){
println("the value at $index is $value")
}
//it will print out as
the value at 0 is a
the value at 1 is b
the value at 2 is c
In here the index of the array is put on the index argument and value is put on the value argument and printed out .

while and do while loop

while loops and do while loop works same as  in java language
var x = 6
while(x < 2 ){
print(x)
 x--
}
var y = 2
do {
y++
}while(y<10)

In here the first while loop will execute the statement x-- means it decreases the value of x by one each time until the condition in the while loop become true and the next is the do while loop where the statement in do will execute until the condition in the while loop becomes true and the difference between while and do while loop is that in do while loop if the condition became true then also it will execute one time before the condition is checked so the result of while loop above will be as
6,4,3 and the result of do while loop will be 3,4,5,6,7,8,9,10 here the the condition is less than 10 but it is executed till 10 that is the difference

 Return statements

The above three are the kotlins structural jump expressions return statement terminates the execution of a function and returns control to the calling function and also can be used to return the value which comes as a result of the function to the calling function by default returns from the nearest enclosing function or anonymous function we can now see an example
var x = 32
var y = 34
fun add (x:Int,y:Int):Int{
 return x+y;
}
print(add(x,y))
//it will output the value as 66

here we have a function called add and it will return the sum of x and y and is printed using the print statement


Thats all for this post guys hope you like the post to get the latest posts on this follow by email and follow me don't forget to share and comment below your doubts and suggestions Thankyou all  

Learn Kotlin 5 (Control Flow:,Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

CONTROL FLOW

The control flow is the way which controls the flow of statements to be executed in here the control flow keywords controls the statement which is to be executed first and there are keywords which can be used to repeat the statements here are the keywords given below

if expression

The if is an expression which returns a value in kotlin as in the english language like after the if keyword a condition is written if the condition is true the statement coming after the if statement will be executed there is also a way in which we can go for a else statement to execute if the if condition become false for example

// it is the traditional way
var name = bas
if (a<b) name = nas
//like other languages there is no terenary operator as "if" works fine here
var id = 123
if (32<33){
            id = 365
}
else{
            id = 284
}
//if as an expression
val name = if (a<b) nas else  jas

if branches can be blocks and the last expression is the value of a block
var mass = if (a>b){
             print("choose a")
             a
}else{
          print ("choose b")
           b
}

one thing to note here is that if you are using if as an expression rather than the statement (like in if statement assigns the value for "mass" in the above statement) then you should include the else branch 

When Expression

The when expression works as switch statement in other c like languages here is an example how when is used as

var name =23
when (name){
1 -> print("the value of name is 1")
2 ->print ("the value of name is 2")
else -> {
      print("value of name is 23")
}
}
in the above sample we can see that the argument in the when expression is given as "name" and the value of "name" is 23 the arguments in the when expression which evaluated sequentially with the branches in the when block like here "name" value is evaluated with 1 and 2 and if the value is same as 1 the output will be "the value of name is 1" and if it is 2 it will print "the value of name is 2"
and if those two values are not evaluated true then the else block will be executed when can be used as a expression or as a statement if it is used as an expression then the value of the satisfied branch becomes the value of the overall expression and if the when used as a statement then the values of the individual branches are ignored as explained above for if expression each branch can be a block and its value is the value of the last expression in the block if  when  is used as an expression then else is mandatory
 if there are many cases are to be handled in the same way we can use comma as example

when (name){
0,1 -> print("the value is either one or zero ")
else->print("the value is 23")
}
We can use arbitrary expressions as branch conditions

when(name){
parseInt(s)->print("the value is s")
else ->  print("otherwise")
 }
We can also check that if the given argument is in the given range or collection with in or !in
when (name){
in 1..10 -> print("name is in the range of 1 to 10")
!in 10..19 ->print("name is not in the range 10 to 19")
else - > print("otherwise")

}



we can also check if the value is certain type or is not using is and !is
when (name){
is String -> print ("the value is a string")
else -> false
}
The when statement can used as a alternative for if else statement if no argument is supplied the branch conditions are simply boolean expressions and a branch is executed when its condition is true
example :

when{
name isodd -> print ("name is odd")
name iseven -> print("name is even")
else -> print("name is nothing") 
}

Thats all for this post guys hope you like the post if any doubts comment below and to get latest updates on my blog follow by email and follow me don't forget to share and comment below thanks

Saturday, June 2, 2018

Learn Kotlin 4 (Basic Types 2 and packages: ,Hi friends this is the continuation of previous post so i kindly request you to read that before this post. As this blog is also prepared for beginners so i advice you that you don't need to by-heart this lessons just read and understand it if you have any doubt ask in the comment section)

Strings

The strings are a sequence of characters either as a literal constant or as some kind of variable in kotlin strings are represented by the type String . strings are immutable and it's characters can be accessed by indexing operation . s[i] a string can be iterated over with a for -loop (for-loop will be explained in the coming lessons ) we can concatenate string using + operator it can also be done for other types also as long the first element in the expression is string here is an example
val a = "abc" + 1
println(a + "nads")

The above code shows how the string abc is concatenated with 1 and then it is printed out as "abc1nads" by concatenating a and nads kotlin has two types of string literals they are escaped string literal and raw strings escaped strings are which that may have escaped characters in them and raw strings are which that can contain new line and arbitary text here is an example of escaped string

val s = "Hello World\n"
here the escaping is done in the conventional way with a backslash
A raw string is delimited by triple quotes contains no escaping and can contain new line any other character example

val o = """for (c in "value")
                     println(c) """
The leading whitespace can be removed using the function trimMargin()
val text = """
                     |this is the first line
                     |this is the second line
                     |this is the third line
                     |this is the fourth line
                 """,trimMargin()

the | is used as margin prefix but you can choose another character and pass it as a parameter like trimMargin('>')

String Template

         strings may contain template expressions means the pieces of code which are evaluated and concatenated with the string which starts with a dollar sign like $a and contains like a simple name or an arbitrary expression in curly braces here is some examples


val i = 14
println("i is $i")
//this prints 'i is 14'
//another one with an arbitrary expression in curly braces
val a = "abc"
println("$a.length is ${s.length}"  )
//prints "abc.length is 3"


Templates are supported both inside the raw string and escape string if you need to represent a literal $ character in a raw string which doesn't support backslash escaping we can use the following syntax given below

val price = """
           $('$')9.99
            """

Packages

The packages is a namespace that contains the set of related classes all the contents such as classes and functions of source file are contained by the package this package is to be declared first in the kotlin project for example
 
package nads.sani
fun me(){}
class myclass{}

So as explained above the me functions full name is nads.sani.me and the full name of myclass is nads.sani.myclass if the package is not specified the contents of such a file belong to default package that has no name. A number of packages are imported to kotlin as default for example
  • kotlin.*
  • kotlin.annotation.*
  • kotlin.collections.*  
  • kotlin.comparison.*
  • kotlin.io.*
  • kotlin.ranges.*
  • kotlin.sequences.*
  • kotlin.text.*
Additional packages are imported depending on the target platform
Like JVM(java):
  • java.lang.*
  • kotlin.jvm.* 
And for Js(Javascript):
  • kotlin.js.*
Imports
Not only default imports there are also other imports can be include in here
We can import either a single name like:

import nads.sani//sani is now accessible without qualification

Or we can include all the accessible files from the nads file by using:

import nads.*//by using the * at last all the files from the nads are included here
And if there is a name clash in our file we can use the as keyword here to use our desired name by changing it to other name in the file for example

import nads.sani //sani is accessible here
import jack.sani as chani  //access the features of jack.sani by using chani

Some facts on imports

  • the import keyword is not only restricted to importing classes can also be used on other declarations like:Top level function and properties,function and properties declared in object declarations,enum constants
  • like in java kotlin doesn't have a "import static" syntax all of this declarations are imported using the regular import keyword

Thats all for this post guys more will be included in the next post hope you like the post to get the latest update on this blog please follow by email or follow me and don't forget to share and comment below