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}")
}
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 likewhere the variables can be changed, increase or decrease
var x = 5 // `Int` type is inferred
x += 1
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
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. */
/* 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:
or an arbitrary expression in curly braces:
var a = 1
// simple name in template:
val s1 = "a is $a"
//prints a is 1
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}")
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
"""
Conditional Expressions
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a }
else {
return b }
}
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
}
// `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)
}
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++
}
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!
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")
} } }
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.
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")
}
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:
Iterating over a collection:
for (item in items) {
println(item)
}
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")
}
"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)}
.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 :
example are like :
val rectangle = Rectangle(5.0, 2.0) //no 'new' keyword required
val triangle = Triangle(3.0, 4.0, 5.0)
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




