a statically typed language for multiple applications.
For Java
.class
bytecode file which depend on classes that are in JRE which we sure it exists.only one pulblic class
For Kotlin
class keyword
and must contain main method..class
file as JVM need itjava Mainkt --classpath kotlind-stdlib.jar ....
.class
divided into two categories:-
Hard | Soft |
---|---|
is reserved all time and in all places | reserved in some scopes |
val, val, fun, class, interface,.. etc | catch (in try clause), import, init , set , constructor, ..etc |
Modifier keywords : are words that modifie hard keywords such as open
, data
, etc
are data container
declared using val
, var
as var a = 10
val | var |
---|---|
immutable data (can not changed) |
mutable data |
must be have intial value |
not neccessary |
can write type or let kotlin infer it so var a = 10
and var a : Int = 10
are same.
kotlin not auto casting for varibles so
var a = 10 var b : Long = a // will raise error although int is smaller than long. var b : Long = a.toLong() // Solution
for convention names start with lower case and use camel case for multiple words.
for a constant variable we use
companion object { const val FIXED_VAL = 100 }
NOTE : should be all upper
, use _
for multpile words, val
as it immutable
Every thing is class
so int, short and other data types are classes
that has functions such as (plus
, times
, toInt
, toLong
, rem
, ..etc).
important point:
a++ | a.inc() |
---|---|
a is increamented | a increamented but to a new variable so a valuenot changed |
when comparing values use ==
rather than .equals
as first one use less code when be compiled as ==
compiler evalute it at compile time.
val a = String() // accept array of character, bytes.
, but val a = String("Hello")
is Worng.indexOf
, substring
, get(int)
.val a = "RED" | const val a = "RED" |
---|---|
converted intoprivate static final String a = "RED"; |
converted into public static final String a = "RED"; |
also create a get Function | does not create and value is evaluted at compile. |
slow | fast |
class Constants { companion object { const val A = "A" @JvmField val B = "B" } } // use them as println(Constants.A) println(Constants.B)
Constants.A
will be replace at compile time into A
Constants.B
will remain same.unit that help us reuse code
same as Java but differs as it can be written outside a class as top-level.
Syntax
fun main(args: Array<String>) { // we can use any arrangment of params as we use named one. // also op param is by default '+' val res = calc(param2 = 12 ,param1 = 8) // res = 20 print(res) } fun calc (param1 : Int ,param2 : Int , op : String = "+" ): Int{ when (op){ // is same as switch in Java "+" -> return param1 + param2 "-" -> return param1 - param2 else -> return -1 } }
here are code with different cases
var a : String? = null println(a) // print null println(a?.length) // print null, you can not use a.length as a is nullable println(a?.length ?: -1 ) // print -1 (Elvis operator ) println(a!!.length) // Cause Kotlin NuLLPointerException.u can use try-catch to handle it
println(a?.length)
is equiv to as check first if it equal to null
it print null
otherwise print value of length.
println(a?.length ?: -1 )
same as last but provide a value instead of 'null'
println(a!!.length)
enforce call to length
and handle exception by yourself.
fun main(args: Array<String>) { val arr = arrayOf(1,2,3,4,5) for(item in arr){ println(item) // print each item in a new line } // until stop at max -1 (i.e max is excluded) for (index in 0 until arr.size){ println(arr.get(index)) // print each item in a new line } // indices return array of index, step 2 means to update each iteration with 2 for(index in arr.indices step 2 ){ println(arr.get(index)) } }
1 2 3 4 5
.1 3 5
.try/catch
to handle exception and provide useable solution to it.we can write functions and wrap them into class to be used from one place
we create a seperate class
write all functions inside companion object
Example:-
class MathLib{ companion object { fun add (param1 : Int, param2 :Int): Int{ return param1.plus(param2) } } }
class
class Student(var name:String, private var _age: Int) { // this is a secondary constructor, it must call primary one constructor():this("na" , 10){ println("Called from secondary ") } // is called after calling to primary constructor init { name = name.toUpperCase() println("Promary is called ") } // make another one, provide a get and set var age : Int = _age get() = field set(value) { field = value} }
private
that make var visible only inside its class and provide set , get for public useKotlin can use Java classes to do things that not provided yet in Kotlin or it may require more code
for example Kotlin does not have concurrency formating so you must handle it explicity (i.e code to add symbol, code to decide local and write suitable symbol).
Expamle:-
val value = 22 println("It costs ${value}$") Locale.setDefault(Locale.US) val formater : NumberFormat = NumberFormat.getCurrencyInstance() println("It costs ${formater.format(value)}") Locale.setDefault(Locale.FRANCE) val formater2 : NumberFormat = NumberFormat.getCurrencyInstance() println("It costs ${value}€") println("It costs ${formater2.format(value)}")
formater
is reponsible of determine suitable currency symbol based on Local
package
keyword.Koltin provide fixed-size collection (Array) and non fixed-size (list, set,map).
Array is a class in Kotlin
if it contains mixed types
its type will be Any
we can create array with a variety of methods
// create array of values (here are of type Any as types are mixed ) val arr = arrayOf("10", 12 , 13 , 14 ) // helper method create nulls of specified type, accept size val arr1Null = arrayOfNulls<String?>(10) // // create array of integer values val arr1 = intArrayOf(22 , 10 ) for(element in arr) println("Value is $element" ) // will dislay null 10 times. for(element in arr1Null) println("Value is $element" ) for(element in arr1) println("Value is $element" ) arr1.sort() for (item in arr1) println(item) // 10 22 arr1.sortedArrayDescending() for (item in arr1) println(item) // 22 10
sort()
change arr content, but sortedArrayDescending()
return a new obj.List, Set, Map comes with two version Mutable, Immutable.
List is same as Array but with facilty of adding
and removing
items.
Sets areun-ordered unique elements.
Map is a key-value data structure which store data chained with a key.
Example:-
// this is Immutable list so can not add/remove from it val list = listOf("Ahmed" , "Mahmoud") // this is mutable list val mulList = mutableListOf("Ahmed" , "Mahmoud") mulList.add("Hafez") mulList.add(0 , "Hassan") mulList.remove("Ahmed") println(mulList) // [Hassan, Mahmoud, Hafez] // this is Immutable Set so can not add/remove from it val set = setOf(1,2,3,2,4,5) // this is mutable Set val mulset = mutableSetOf<Int>(1,2,3,2,4,5) println(mulset) // [1, 2, 3, 4, 5] NOTE 2 is displayed only one time // this is mutable Map val map = mutableMapOf(Pair("Ahmed" , 22) , Pair("Mahmoud" , 23)) // put is used to add Pairs(Key , Value) map.put("Hassan" , 21 ) // display values is by calling get(key) or use this trick for ((name , age) in map) println(" name : $name and Age is $age")
listOf<>()
in angle brackets we can write type or let Kotlin to determine it.Parent
and Child
.Any
is like Object
at Java (all classes inherit from it).open class Animal (val color: String) { fun walk(){ println("I am Walking") } override fun toString(): String { return "Animal with ${color}" } } class Dog(color: String) : Animal(color ){ override fun toString(): String { return super.toString() + this::class.simpleName } }
fun main(args: Array<String>) { val lol = Retriever() val moly = Sealer() makeSpeak(lol) makeSpeak(moly) // make an anonymous object makeSpeak(object : Cat { override fun speak() { println("Anonymous") super.speak() } }) } fun makeSpeak(cat : Cat){ cat.speak() } interface Cat { fun speak(){ println("Cat") } } interface Lion { fun speak(){ println("Lion") } } class Retriever : Cat , Lion { override fun speak() { // super.speak() // error, conflict there several implementation super<Cat>.speak() println("Retriever ") } } class Sealer : Cat , Lion { override fun speak() { super<Lion>.speak() println("Sealer ") } } /* Output:- Cat Retriever Lion Sealer Anonymous Cat */Notes
conflict
when two or more interface have same method like speak
and try to call super.speak which will raise error so Solution with super<Cat>.speak()
makeSpeak
is example of using polymorphism as it accept any obj from type of Cat
as it run with sealer
, retriever
which are if type Cat
object : Cat {}
it seems as we create a concreate class that implements Cat and make object from it.val sayHallo = { name : String, age : Int -> println("hello $name and age $age") } sayHallo("Ahmed" , 21 ) sayHallo.invoke("Ahmed" , 21 ) println(sayHallo::class.simpleName) val arr = arrayOf("Ahmed" , "Mohamed" , "Ali") // item represent a element from array is sent as parameter to sorted by val sorted = arr.sortedBy { item : String -> item.length } println(sorted) // use it as we expect only one paramter val filtered = arr.filter { it.startsWith("A")} println(filtered) /* Output:- hello Ahmed and age 21 hello Ahmed and age 21 sayHallo$1 [Ali, Ahmed, Mohamed] [Ahmed, Ali] */Note
sayHallo
is treated as object.sayHallo::class.simpleName
it prints sayHallo$1
indicates its of type sayHallosortedBy
expect a Predicat that accept a string and return a value to sort based on it.it
as in arr.filter { it.startsWith("A")}
filter used to select items based on selection criteria
passed as lambda.data
keyword before class and provide properties as primary constructor.setter
, getter
, toString
, hashCode
methods by default.data class Item (var name : String , var price : Float )
fun main(args: Array<String>) { val item1 = Shirt( "XL",21.4 ) val item2 = Paints( "XX",25.4 ) val mostexpensive = if (item1.price > item2.price) item1 else item2 val instriction = when(mostexpensive){ is Shirt -> "Button it!" is Paints -> "Buckle it!" } println(instriction) // Buckle it! } sealed class ClothingItem (val type:String){ abstract val size:String abstract val price:Double } data class Shirt(override val size: String, override val price: Double) : ClothingItem("Shirt") data class Paints(override val size: String, override val price: Double) : ClothingItem("Paints")Note: in
when
statement if you not write all cases of sealed class or provide else
so compiler will raise an error as compiler all types of sealed class.Thanks to Allah, last update 23/9/2019