& Android Android Best Practices and Advance Kotlin Kotlin and Android 1
About Me • Muhammad Atif • Work at Telenor • My favorite language is Java & Kotlin • Love Hiking Kotlin and Android 2
Table of Content Basic Syntax Advance Kotlin Android Best Pratices Kotlin and Android 3
What Kotlin is Not Kotlin and Android 4
Kotlin programming language, design goals • Concise: • Reduce the amount of code • Safe • No more NullPointerExceptions • Val name = data?.getStringExtra(NAME) • Interoperable • Use existing libraries for JVM (like Android API) • Compile to JVM or JavaScript • Tool-friendly • Support for the programmer using editors (like Android Studio) Kotlin and Android 5
Kotlin, a little syntax • Semicolons are optional • Adding a new-line is generally enough • Variables and constants • var name = ”Atif” // variable • var means ”variable” • val name2 = ” Atif” // read-only (constant) • val means ”value” • Types are not specified explicity by the programmer • Types are infered by the compiler Kotlin and Android 6
• var • val • lateinit • lazy • getters • setters Kotlin and Android 7 Data types , variable declaration and initialization
• Mutable. • non-final variables. • Once initialized, we’re free to mutate/change the data held by the variable. For example, in Kotlin: var myVariable = 1 • read-only/nonmutable/imutable. • The use of val is like declaring a new variable in Java with the final keyword. For example, in Kotlin: val name: String = "Kotlin" Kotlin and Android 8 Difference b/w var & val Kotlin’s keyword .
• lateinit means late initialization. • If you do not want to initialize a variable in the constructor instead you want to initialize it later • if you can guarantee the initialization before using it, then declare that variable with lateinit keyword. • It will not allocate memory until initialized. • It means lazy initialization. • Your variable will not be initialized unless you use that variable in your code. • It will be initialized only once after that we always use the same value. Kotlin and Android 9 How Kotlin Keywords & delegate, Lateinit & Lazy works?
setters are used for setting value of the property. Kotlin internally generates a default getter and setter for mutable properties using var. Property type is optional if it can be inferred from the initializer. set(value) getters are used for getting value of the property. Kotlin internally generates a getter for read-only properties using val. The getter is optional in kotlin. Property type is optional if it can be inferred from the initializer. get() = value Kotlin and Android 10 How Kotlin Properties,getter & setter works?
Kotlin and Android 11 Nullable Types and Null Safety in Kotlin • Kotlin supports nullability as part of its type System. That means You have the ability to declare whether a variable can hold a null value or not. • By supporting nullability in the type system, the compiler can detect possible NullPointerException errors at compile time and reduce the possibility of having them thrown at runtime. var greeting: String = "Hello, World" greeting = null // Compilation Error • To allow null values, you have to declare a variable as nullable by appending a question mark in its type declaration - var nullableGreeting: String? = "Hello, World“ nullableGreeting = null // Works Safety Checks • Adding is initialized check if (::name.isInitialized) • Adding a null Check • Safe call operator: ? val name = if(null != nullableName) nullableName else "Guest“ • Elvis operator: ‘ ?: ’ val b = a?.length ?: -1 • Not null assertion : !! Operator • Nullability Annotations @NotNull
Kotlin and Android 12 Nullability and Collections • Kotlin’s collection API is built on top of Java’s collection API but it fully supports nullability on Collections. Just as regular variables are non-null by default, a normal collection also can’t hold null values. val regularList: List<Int> = listOf(1, 2, null, 3) // Compiler Error • Collection of Nullable Types val listOfNullableTypes: List<Int?> = listOf(1, 2, null, 3) // Works • To filter non-null values from a list of nullable types, you can use the filterNotNull() function . val notNullList: List<Int> =listOfNullableTypes.filterNotNull() var listOfNullableTypes: List<Int?> = listOf(1, 2, null, 3) // Works listOfNullableTypes = null // Compilation Error var nullableList: List<Int>? = listOf(1, 2, 3) nullableList = null // Works var nullableListOfNullableTypes: List<Int?>? = listOf(1, 2, null, 3) // Works nullableListOfNullableTypes = null // Works
Kotlin and Android 13 Kotlin Operators Just like other languages, Kotlin provides various operators to perform computations on numbers. • Arithmetic operators (+, -, *, /, %) • Comparison operators (==, !=, <, >, <=, >=) • Assignment operators (+=, -=, *=, /=, %=) • Increment & Decrement operators (++, --) Operations on Numeric Types Expression Translates to a + b a.plus(b) a - b a.minus(b) a * b a.times(b) a / b a.div(b) a % b a.rem(b) a++ a.inc() a−− a.dec() a > b a.compareTo(b) > 0 a < b a.compareTo(b) < 0 a += b a.plusAssign(b)
Kotlin and Android 14 Kotlin Control Flow • If-Else Statement • When Expression(Switch) • For Loop • For Each Loop • While Loop • do-while loop • Break and Continue
Kotlin and Android 15 Kotlin Functions • Unit returning Functions Functions which don’t return anything has a return type of Unit. The Unit type corresponds to void in Java. fun printAverage(a: Double, b: Double): Unit { println("Avg of ($a, $b) = ${(a + b)/2}") } • Single Expression Functions fun avg(a: Double, b: Double): Double { return (a + b)/2 } avg(4.6, 9.0) // 6.8
Kotlin and Android 16 Kotlin Functions • Defining and Calling Functions You can declare a function in Kotlin using the fun keyword. Following is a simple function that calculates the average of two numbers . Syntax: fun functionName(param1: Type1, param2: Type2,..., paramN: TypeN): Type { // Method Body } For Example: fun avg(a: Double, b: Double): Double { return (a + b)/2 } avg(4.6, 9.0) // 6.8
Kotlin and Android 17 Kotlin extensions/ Utility Functions add new function to the classes. • Can add new function to class without declaring it. • The new function added behaves like static • Extensions can become part of your own classes & predefined classes. Example: val firstName=“hello” val secondName=“hello” val thirdName=“hello” fun String.add(firstname :String,secondName:String){ retrun this + firstName+secondName; }
Kotlin and Android 18 Kotlin infix Functions Infix function can be a member function or extension function. Properties : • They have single parameter. • They have prefix of infix. For example: infix fun Int.greaterValue(other:Int):Int { If(this>other){ return this }else{ return other }} val greaterVal= x greaterValue y
Kotlin and Android 19 Kotlin tailRec[recursive] Functions Uses recursion in a optimized way. • Prevents stack over flow exception. • Prefix of tailrec is used. For example: tailrec fun getFibonacciNumber(n: Int, a: BigInteger, b: BigInteger): BigInteger { if (n == 0) return b }else{ return getFibonacciNumber(n - 1, a + b, a) }
Kotlin and Android 20 Object Oriented Kotlin for Android Classes • data class User(var name:String,var age:Int) • Compiler generate getters and setters for java Interoperability . • Compiler generate equal() and hashCode(). • Compiler generate copy() method –flexible clone() replacement.
Kotlin and Android 21 Object Oriented Kotlin for Android Classes Example : var user1= User(“name1”,10) var user2=User=(“name1”,10) If(user1==user2){ println(“equal”) }else{ println(“not equal”) } var newUser=user1.copy()//.copy(name=“name”)
Kotlin and Android 22 Object Oriented Kotlin for Android Primary Constructor • Init block • Primary constructor with property • Primary constructor with parameter. For Example : data class User(var name:String,var age:Int)
Kotlin and Android 23 Object Oriented Kotlin for Android Secondary Constructor • Init block. • Keyword constructor. • Can not declare properties in secondary constructor. For Example : data class User(var name:String){ constructor(n:String,id :Int): this(n){ //body } }
Kotlin and Android 24 Object Oriented Kotlin for Android • primary constructor with param class Student1(name:String){ init{ println("name of student : ${name}") } } • primary constructor class Student(var name:String){ init{ println("name of student : ${name}") } } • primary & secondary constructor class User(var name:String){ init{ println("name of student : ${name}") } constructor(n:String,id :Int): this(n){ //body } }
Kotlin and Android 25 Object Oriented Kotlin for Android Inheritance • default classes are public . • final for inheritance you need to make class ‘open’ in koltin . Child classes or derived classes.
Kotlin and Android 26 Object Oriented Kotlin for Android Inheritance • Single level Inheritance • Multi Level inheritance • Hierarchical inheritance
Kotlin and Android 27 Visibility modifier in Kotlin Kotlin Supports • Public • Private • Internal • protected
Kotlin and Android 28 abstract Class, Methods & Properties Classes can be abstract in Nature. • abstract key is by default open in nature. • Abstract class is partially defined class • Abstract method have no body when declared • Abstract property can not be initialized when declared. • You can not create instance of abstract class • You need to override abstract properties & method in derived class.
Kotlin and Android 29 Interfaces in Kotlin Listeners ,call back , services in koltin. • Interface keyword Is used . • Short or temporary service. • Whatever you define in interface is by default abstract in nature. • You need to override abstract properties & method in derived class. • Interface can contains normal and abstract methods.
Kotlin and Android 30 Object Declaration and companion Objects WHAT IS SINGLETON IN KOTLIN.? • One INSTANCE of class in whole application. • Single object will be created internally. • We can not declare “static” variable or objects in kotlin as compared to java. • Declare “object”. • This will create a singleton object for us when programs runs. • We can have properties , methods, initializers • Can not have constructor. i:e we can not create instance manually. • Object can have super class, supports inheritance.
Kotlin and Android 31 Object Declaration and companion Objects Example: Object Customer{ init{ } var id:Int=0 fun getId():Integer{ return id; } }
Kotlin and Android 32 Object Declaration and companion Objects Companion Objects. • Same as object but declared within a particular class. Example: Class MyClass{ companion object { var count:Id=1 fun voidFun(){//body} } }
Kotlin and Android 33 Using the Data Binding Library Data Binding • automatically generates the classes required to bind the views in the layout with your data objects. • One way data binding. • Two way data binding.
Kotlin and Android 34 Using the Data Binding Library 1 way vs. two way Data Binding • One-way data-binding means the data flows in a single direction so that whenever the data changes in a component, it also updates the view with new data. • Two-way data binding means data flows in both directions, it means any change happens in the view updates the data and any change happens in the data updates the view.
Kotlin: no more findViewById(…) • Import kotlinx.android.synthetic.main.activity_main.* • activity_main.xml is the name of the layout file • var word = mainWordEditText.text • mainWordEditText is the id from the layout file • mainClearWordsButton.setOnClickListener { /*do something*/ } • mainClearWordsButton is the id from the layout file Kotlin and Android 35
Android Development Best Practices Here are some additional best practices you should follow when building Android apps: • Use the recommended Android architecture. • Always maintain the code quality. • Create separate layouts for UI elements that will be re-used. • Detecting and fixing memory leaks in android. • Always include unit tests. • Always include functional UI tests. Kotlin and Android 36
Android Development Best Practices • Avoid deep levels in layouts. • Use the Parcelable class instead of Serializable when passing data in Intents or Bundles. • Perform file operations off the UI thread. Kotlin and Android 37
Kotlin and Android 38 Advance Kotlin for Android • Clean Architecture using MVVM • Design Patterns • RXJava2 • Dagger2( Dependency Injection) • Retrofit • DataBinding(Google) • Clean Architecture using MVVM/MVI • Coroutines /Flow/LiveData • Koin ( Dependency Injection) • Retrofit • DataBinding (Synthetic Kotlin) PART 2 PART 3 To be continued.!!

Introduction to Koltin for Android Part I

  • 1.
    & Android Android BestPractices and Advance Kotlin Kotlin and Android 1
  • 2.
    About Me • MuhammadAtif • Work at Telenor • My favorite language is Java & Kotlin • Love Hiking Kotlin and Android 2
  • 3.
    Table of Content BasicSyntax Advance Kotlin Android Best Pratices Kotlin and Android 3
  • 4.
    What Kotlin isNot Kotlin and Android 4
  • 5.
    Kotlin programming language,design goals • Concise: • Reduce the amount of code • Safe • No more NullPointerExceptions • Val name = data?.getStringExtra(NAME) • Interoperable • Use existing libraries for JVM (like Android API) • Compile to JVM or JavaScript • Tool-friendly • Support for the programmer using editors (like Android Studio) Kotlin and Android 5
  • 6.
    Kotlin, a littlesyntax • Semicolons are optional • Adding a new-line is generally enough • Variables and constants • var name = ”Atif” // variable • var means ”variable” • val name2 = ” Atif” // read-only (constant) • val means ”value” • Types are not specified explicity by the programmer • Types are infered by the compiler Kotlin and Android 6
  • 7.
    • var • val •lateinit • lazy • getters • setters Kotlin and Android 7 Data types , variable declaration and initialization
  • 8.
    • Mutable. • non-finalvariables. • Once initialized, we’re free to mutate/change the data held by the variable. For example, in Kotlin: var myVariable = 1 • read-only/nonmutable/imutable. • The use of val is like declaring a new variable in Java with the final keyword. For example, in Kotlin: val name: String = "Kotlin" Kotlin and Android 8 Difference b/w var & val Kotlin’s keyword .
  • 9.
    • lateinit meanslate initialization. • If you do not want to initialize a variable in the constructor instead you want to initialize it later • if you can guarantee the initialization before using it, then declare that variable with lateinit keyword. • It will not allocate memory until initialized. • It means lazy initialization. • Your variable will not be initialized unless you use that variable in your code. • It will be initialized only once after that we always use the same value. Kotlin and Android 9 How Kotlin Keywords & delegate, Lateinit & Lazy works?
  • 10.
    setters are usedfor setting value of the property. Kotlin internally generates a default getter and setter for mutable properties using var. Property type is optional if it can be inferred from the initializer. set(value) getters are used for getting value of the property. Kotlin internally generates a getter for read-only properties using val. The getter is optional in kotlin. Property type is optional if it can be inferred from the initializer. get() = value Kotlin and Android 10 How Kotlin Properties,getter & setter works?
  • 11.
    Kotlin and Android11 Nullable Types and Null Safety in Kotlin • Kotlin supports nullability as part of its type System. That means You have the ability to declare whether a variable can hold a null value or not. • By supporting nullability in the type system, the compiler can detect possible NullPointerException errors at compile time and reduce the possibility of having them thrown at runtime. var greeting: String = "Hello, World" greeting = null // Compilation Error • To allow null values, you have to declare a variable as nullable by appending a question mark in its type declaration - var nullableGreeting: String? = "Hello, World“ nullableGreeting = null // Works Safety Checks • Adding is initialized check if (::name.isInitialized) • Adding a null Check • Safe call operator: ? val name = if(null != nullableName) nullableName else "Guest“ • Elvis operator: ‘ ?: ’ val b = a?.length ?: -1 • Not null assertion : !! Operator • Nullability Annotations @NotNull
  • 12.
    Kotlin and Android12 Nullability and Collections • Kotlin’s collection API is built on top of Java’s collection API but it fully supports nullability on Collections. Just as regular variables are non-null by default, a normal collection also can’t hold null values. val regularList: List<Int> = listOf(1, 2, null, 3) // Compiler Error • Collection of Nullable Types val listOfNullableTypes: List<Int?> = listOf(1, 2, null, 3) // Works • To filter non-null values from a list of nullable types, you can use the filterNotNull() function . val notNullList: List<Int> =listOfNullableTypes.filterNotNull() var listOfNullableTypes: List<Int?> = listOf(1, 2, null, 3) // Works listOfNullableTypes = null // Compilation Error var nullableList: List<Int>? = listOf(1, 2, 3) nullableList = null // Works var nullableListOfNullableTypes: List<Int?>? = listOf(1, 2, null, 3) // Works nullableListOfNullableTypes = null // Works
  • 13.
    Kotlin and Android13 Kotlin Operators Just like other languages, Kotlin provides various operators to perform computations on numbers. • Arithmetic operators (+, -, *, /, %) • Comparison operators (==, !=, <, >, <=, >=) • Assignment operators (+=, -=, *=, /=, %=) • Increment & Decrement operators (++, --) Operations on Numeric Types Expression Translates to a + b a.plus(b) a - b a.minus(b) a * b a.times(b) a / b a.div(b) a % b a.rem(b) a++ a.inc() a−− a.dec() a > b a.compareTo(b) > 0 a < b a.compareTo(b) < 0 a += b a.plusAssign(b)
  • 14.
    Kotlin and Android14 Kotlin Control Flow • If-Else Statement • When Expression(Switch) • For Loop • For Each Loop • While Loop • do-while loop • Break and Continue
  • 15.
    Kotlin and Android15 Kotlin Functions • Unit returning Functions Functions which don’t return anything has a return type of Unit. The Unit type corresponds to void in Java. fun printAverage(a: Double, b: Double): Unit { println("Avg of ($a, $b) = ${(a + b)/2}") } • Single Expression Functions fun avg(a: Double, b: Double): Double { return (a + b)/2 } avg(4.6, 9.0) // 6.8
  • 16.
    Kotlin and Android16 Kotlin Functions • Defining and Calling Functions You can declare a function in Kotlin using the fun keyword. Following is a simple function that calculates the average of two numbers . Syntax: fun functionName(param1: Type1, param2: Type2,..., paramN: TypeN): Type { // Method Body } For Example: fun avg(a: Double, b: Double): Double { return (a + b)/2 } avg(4.6, 9.0) // 6.8
  • 17.
    Kotlin and Android17 Kotlin extensions/ Utility Functions add new function to the classes. • Can add new function to class without declaring it. • The new function added behaves like static • Extensions can become part of your own classes & predefined classes. Example: val firstName=“hello” val secondName=“hello” val thirdName=“hello” fun String.add(firstname :String,secondName:String){ retrun this + firstName+secondName; }
  • 18.
    Kotlin and Android18 Kotlin infix Functions Infix function can be a member function or extension function. Properties : • They have single parameter. • They have prefix of infix. For example: infix fun Int.greaterValue(other:Int):Int { If(this>other){ return this }else{ return other }} val greaterVal= x greaterValue y
  • 19.
    Kotlin and Android19 Kotlin tailRec[recursive] Functions Uses recursion in a optimized way. • Prevents stack over flow exception. • Prefix of tailrec is used. For example: tailrec fun getFibonacciNumber(n: Int, a: BigInteger, b: BigInteger): BigInteger { if (n == 0) return b }else{ return getFibonacciNumber(n - 1, a + b, a) }
  • 20.
    Kotlin and Android20 Object Oriented Kotlin for Android Classes • data class User(var name:String,var age:Int) • Compiler generate getters and setters for java Interoperability . • Compiler generate equal() and hashCode(). • Compiler generate copy() method –flexible clone() replacement.
  • 21.
    Kotlin and Android21 Object Oriented Kotlin for Android Classes Example : var user1= User(“name1”,10) var user2=User=(“name1”,10) If(user1==user2){ println(“equal”) }else{ println(“not equal”) } var newUser=user1.copy()//.copy(name=“name”)
  • 22.
    Kotlin and Android22 Object Oriented Kotlin for Android Primary Constructor • Init block • Primary constructor with property • Primary constructor with parameter. For Example : data class User(var name:String,var age:Int)
  • 23.
    Kotlin and Android23 Object Oriented Kotlin for Android Secondary Constructor • Init block. • Keyword constructor. • Can not declare properties in secondary constructor. For Example : data class User(var name:String){ constructor(n:String,id :Int): this(n){ //body } }
  • 24.
    Kotlin and Android24 Object Oriented Kotlin for Android • primary constructor with param class Student1(name:String){ init{ println("name of student : ${name}") } } • primary constructor class Student(var name:String){ init{ println("name of student : ${name}") } } • primary & secondary constructor class User(var name:String){ init{ println("name of student : ${name}") } constructor(n:String,id :Int): this(n){ //body } }
  • 25.
    Kotlin and Android25 Object Oriented Kotlin for Android Inheritance • default classes are public . • final for inheritance you need to make class ‘open’ in koltin . Child classes or derived classes.
  • 26.
    Kotlin and Android26 Object Oriented Kotlin for Android Inheritance • Single level Inheritance • Multi Level inheritance • Hierarchical inheritance
  • 27.
    Kotlin and Android27 Visibility modifier in Kotlin Kotlin Supports • Public • Private • Internal • protected
  • 28.
    Kotlin and Android28 abstract Class, Methods & Properties Classes can be abstract in Nature. • abstract key is by default open in nature. • Abstract class is partially defined class • Abstract method have no body when declared • Abstract property can not be initialized when declared. • You can not create instance of abstract class • You need to override abstract properties & method in derived class.
  • 29.
    Kotlin and Android29 Interfaces in Kotlin Listeners ,call back , services in koltin. • Interface keyword Is used . • Short or temporary service. • Whatever you define in interface is by default abstract in nature. • You need to override abstract properties & method in derived class. • Interface can contains normal and abstract methods.
  • 30.
    Kotlin and Android30 Object Declaration and companion Objects WHAT IS SINGLETON IN KOTLIN.? • One INSTANCE of class in whole application. • Single object will be created internally. • We can not declare “static” variable or objects in kotlin as compared to java. • Declare “object”. • This will create a singleton object for us when programs runs. • We can have properties , methods, initializers • Can not have constructor. i:e we can not create instance manually. • Object can have super class, supports inheritance.
  • 31.
    Kotlin and Android31 Object Declaration and companion Objects Example: Object Customer{ init{ } var id:Int=0 fun getId():Integer{ return id; } }
  • 32.
    Kotlin and Android32 Object Declaration and companion Objects Companion Objects. • Same as object but declared within a particular class. Example: Class MyClass{ companion object { var count:Id=1 fun voidFun(){//body} } }
  • 33.
    Kotlin and Android33 Using the Data Binding Library Data Binding • automatically generates the classes required to bind the views in the layout with your data objects. • One way data binding. • Two way data binding.
  • 34.
    Kotlin and Android34 Using the Data Binding Library 1 way vs. two way Data Binding • One-way data-binding means the data flows in a single direction so that whenever the data changes in a component, it also updates the view with new data. • Two-way data binding means data flows in both directions, it means any change happens in the view updates the data and any change happens in the data updates the view.
  • 35.
    Kotlin: no morefindViewById(…) • Import kotlinx.android.synthetic.main.activity_main.* • activity_main.xml is the name of the layout file • var word = mainWordEditText.text • mainWordEditText is the id from the layout file • mainClearWordsButton.setOnClickListener { /*do something*/ } • mainClearWordsButton is the id from the layout file Kotlin and Android 35
  • 36.
    Android Development BestPractices Here are some additional best practices you should follow when building Android apps: • Use the recommended Android architecture. • Always maintain the code quality. • Create separate layouts for UI elements that will be re-used. • Detecting and fixing memory leaks in android. • Always include unit tests. • Always include functional UI tests. Kotlin and Android 36
  • 37.
    Android Development BestPractices • Avoid deep levels in layouts. • Use the Parcelable class instead of Serializable when passing data in Intents or Bundles. • Perform file operations off the UI thread. Kotlin and Android 37
  • 38.
    Kotlin and Android38 Advance Kotlin for Android • Clean Architecture using MVVM • Design Patterns • RXJava2 • Dagger2( Dependency Injection) • Retrofit • DataBinding(Google) • Clean Architecture using MVVM/MVI • Coroutines /Flow/LiveData • Koin ( Dependency Injection) • Retrofit • DataBinding (Synthetic Kotlin) PART 2 PART 3 To be continued.!!