Pages

Thursday, May 10, 2018

LEARN KOTLIN 2(BASIC SYNTAX)

                                     BASIC SYNTAX

                        First we must add the package specification means A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. and also some import statements should be added example "import java.util " which is like the package which contains specific set of tools which can be used to implement certain tasks like It contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).    
               
                    
package my.demo

import java.util.*

// ...
 
 

                   FUNCTIONS 

The function is started with the fun key word followed by a function name which is to be given by you then a bracket where we need to place our parameters the parameters are certain values where the function works on and then returns a result then the parameters are followed by the return types to know about data types click here :different models of function are given below first function with integer parameters and integer 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}")
 }

for more details on function you can click this link here

Define Variables

      variables can be assigned in two ways they are like mutable variables like
where the variables can be changed, increase or decrease       

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

The other type of variable is the immutable variable type where variables cant be changed


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


                                       COMMENTS

the comments are In programming, comments are portion of the program intended for you and your fellow programmers to understand the code. They are completely ignored by the Kotlin compiler (Kompiler). Just like Java and JavaScript, Kotlin supports end-of-line and block comments.
examples are given below
 

// This is an end-of-line comment
 /* This is a block comment on multiple lines. */


                                       String Templates 

 

the string template is kotlin's good feature which the Strings may contain template expressions, i.e. pieces of code that are evaluated and whose results are concatenated into the string. A template expression starts with a dollar sign ($) and consists of either a simple name:

var a = 1 // simple name in template:
val s1 = "a is $a"
//prints a is 1



or an arbitrary expression in curly braces:
val s = "abc"
println("$s.length is ${s.length}") 
// prints "abc.length is 3"
Templates are supported both inside raw strings and inside escaped strings. If you need to represent a literal $ character in a raw string (which doesn't support backslash escaping), you can use the following syntax:
val price = """ ${'$'}9.99 """


To get more on string template click here

                              Conditional Expressions 

 

fun maxOf(a: Int, b: Int): Int {
if (a > b) {
 return a }
else {
 return b }
}
The if-else expression in here works as the condition comes after the "if"  statement in the bracket is true then the statement that comes after the "if" statement will work else the statement that comes after "else" statement will work


                   Using nullable values and checking for null

A reference must be explicitly marked as nullable when null value is possible.to know more about null safety and its details click here

 
The is operator checks if an expression is an instance of a type. If an immutable local variable or property is checked for a specific type, there's no need to cast it explicitly:
fun getStringLength(obj: Any): Int? { if (obj is String) {
 // `obj` is automatically cast to `String` in this branch return obj.length
} //`obj` is still of type `Any` outside of the type-checked branch return null
 }
OR
fun getStringLength(obj: Any): Int? { if (obj !is String) return null // `obj` is automatically cast to `String` in this branch return obj.length }


                           More Will Be included in the coming chapters about classes and type casts

                                 USING for LOOPS

val items = listOf("apple", "banana", "kiwifruit")
 for (item in items) {
 println(item)
}
The "for" loop here is working like here the values in the items are put in to item as one by one and the code in the curly bracket is executed

                              Using while loop

val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
 index++
 }
while loop and do-while loop these are certain statements used the while loop will execute the code in the curly bracket until the condition in the bracket is true and in do-while loop the code in the curly bracket is executed until the condition in the while loop statement is true
do {
val y = retrieveData()
 } while (y != null) // y is visible here!

                              Using when expression

when (x) {
 1 -> print("x == 1")
 2 -> print("x == 2")
else -> {
// Note the block
print("x is neither 1 nor 2")
 } }  }

when matches its argument against all branches sequentially until some branch condition is satisfied. when can be used either as an expression or as a statement. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored. (Just like with if, each branch can be a block, and its value is the value of the last expression in the block.)

The else branch is evaluated if none of the other branch conditions are satisfied. If when is used as an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions.

                                      Using ranges

The range method Check if a number is within a range using in operator:
val x = 10
val y = 9
 if (x in 1..y+1) {
 println("fits in range")
}
It will iterate over the given range
                                 

                                        USING COLLECTIONS

A generic collection of elements Methods in this interface support only read-only access to the collection; read/write access is supported through the Mutable collection interface.

Iterating over a collection:
for (item in items) {
println(item)
 }
Checking if a collection contains an object using in operator:
when {
 "orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
 }
Using lambda expressions to filter and map collections:
fruits
.filter { it.startsWith("a")}
.sortedBy { it }
 .map { it.toUpperCase() }
 .forEach {println(it)}

               Creating basic classes and their instances:

a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).In kotlin the
example are like :

val rectangle = Rectangle(5.0, 2.0) //no 'new' keyword required
val triangle = Triangle(3.0, 4.0, 5.0)
More on classes will be on the coming posts







THANKS FOR VIEWING THIS BLOG HOPE YOU LIKED AND LEARNED FROM THIS BLOG TO INCLUDE MORE FOR THIS BLOG PLEASE SHARE AND COMMENT I WILL MAKE (I.A) THIS BLOG AS SIMPLE AS POSSIBLE FOR LEARNERS

START KOTLIN 1


Hi friends lets start to learn kotlin i will make it as simple as possible its is also prepared for beginners so for them i advice not to by heart this lessons just understand it

 

                          Kotlin is a functional language and very easy to learn the syntax is very similar to java code so those who know java will be a great advantage  it is accepted as the first official language of android development

                              First we need to install java 8: Kotlin runs on JVM, hence. it is really necessary to use JDK 8 for your local Kotlin development. you have to set the environment variable for JAVA such that it can work properly if you dont know then you can google it. To verify your installation in Windows operating system, hit “java –version” in the command prompt and as an output it will show you the java version installed in your system. To install java go to this link  and install version jdk8 or above.

                            And then you have to install an IDE for your work you can install any one which works with kotlin for example NetBeans,Intellij,Eclipse It is always recommended to use the recent software version to drag out maximum facility from it.

  Starting on IntelliJ IDEA.

Install a recent version of  IntelliJ IDEA kotlin is bounded with IntelliJ IDEA starting from version 15 you can download the community edition from this link

 

 After installing  we need to open it and then in the file menu on the left bar select new -> project->we select the java sdk option kotlin works with java jdk 1.6  Also select the kotlin(java) check box as given above and then click next 

          
   

after that give a name for your project in the options as above i have created my project name as nadeemnew

 and now we have our project created with the folder structure as given above.

Now we need to create kotlin file under the src folder any name can be given i have named here nads select the src file right click select file and then select kotlin File/Class you can see it on the above image once we have the file created we need to type the main routine which is the entry point to the kotlin application In our IDE IntelliJ IDEA offers us a template to do this quickly 

just type main in the file we created and press tab there will be a function created as below 

and here we have added a println () statement which will print the statement in the braces

fun main(args: Array<String>) { println("Hello, World!") }
okay now after typing this code we need to run the application for that we can
select the run menu on the right pane of the menu bar there select the kotlin file
to run and then press the run or there will be run symbol in the main function 
left part click there and select the kotlin file if there is no problem the
application will work well and the result will be shown in the run tool window 
as given below
 
 
 now we have our first kotlin programme running see you in the next post there we 
will learn about basic syntax of kotlin  
 
           
 
 

Thats all for this post friends hope you like this post please share my blog and comment your suggestions so that i can improve this post for an easy learning of kotlin language.And if you wish you to get latest updates on this lesson then follow by email id  or follow me