This document provides an overview of Kotlin and best practices for building apps with Kotlin. Some key points:
- Kotlin is a statically typed language that runs on the JVM and is fully interoperable with Java. It adds features like null safety, lambdas, and concise syntax.
- Kotlin is perfect for Android development as it is compiled to Java bytecode and has full support for Android APIs. The migration process from Java to Kotlin is gradual.
- Best practices for Kotlin include using features like data classes, when expressions, higher order functions, and Android extensions to write more concise and readable code compared to Java.
9. Kotlin - Syntax
• Types follow variable/function names
• Functions start with fun keyword
• Default constructor in class signature
• Semicolons not required
10. Kotlin - Syntax
private fun sum(first: Int , second: Int): Int
{
return first + second
}
Access modifier
Keyword
Function name
Param name
Param type
Return type
11. Kotlin - Syntax
// Omit access modifier
fun sum(a: Int , b: Int): Int {
return a + b
}
// Inline return
fun sum(a: Int , b: Int): Int = a + b
// Omit return type
fun sum(a: Int , b: Int) = a + b
12. Kotlin - Syntax
val name: String ="John" // final
var name: String ="John" //Mutable
ex: name= "Johnny"
Two types of variables
val name ="John" // Types are auto-inferred
14. Kotlin - Null Safety
NULLS ARE PART OF THE TYPE SYSTEM
15. Kotlin - Null Safety
Types default to non-nullable
Mark nullable with the addition of a ?
var a: String = "abc"
a = null
var b: String? = "abc"
b = null
var l = a.length
var l = b.length
// compilation error
// OK
// error: variable 'b' can be null
30. “I don’t want to convert my entire
codebase to a new language.”
Common Concerns
31. •Compiled to byte code (like Java)
•No impact on performance
•Some Kotlin code faster
•Lambdas that can be inlined
•Built-in operations faster than DIY implementations
Kotlin
32. How to migrate
Start in small steps -
Convert a Java / Android app (side project)
Try the kotlin plugin converter
Understand how code is converted from Java to Kotlin
Experiment with kotlin features and tweak code
33. •Add Gradle dependencies (plugin, runtime, etc.)
•Start writing .kt files instead of .java ones
•No need to migrate everything at once
•Kotlin classes can co-exist with Java ones
• IntelliJ has a Java-to-Kotlin converter
•Not perfect but good start
• Works with pasted code
Try kotlin
43. public class Person {
private String name;
private String surname;
private String id;
/*
Setters and getters - 20 lines
*/
@Override public boolean equals(Object o) {
//another few lines here
}
@Override public int hashCode() {
//some more lines
}
@Override public String toString() {
//some more
}
}
Data classes
44. Kotlin -
data class Person(
val name: String,
var surname: String = "",
val id: String
)
Data classes
45. Kotlin - Data classes
equals() & hashCode()
toString()
copy() function
46. fun evaluateObject(obj: Any): String {
return when(obj){
is String -> "Ahoy !!"
is Int -> "Lucky no is $obj"
else -> "Object is in space"
}
}
Kotlin
When expression
49. for (i in 1..100) { ... }
for (i in 0 until 100) { ... }
for (i in 2..10 step 2) { ... }
for (i in 10 downTo 1) { ... }
if (x in 1..10) { ... }
Android Kotlin tricks
56. class MyActivity : AppCompactActivity(){
// wont be init here
lateinit var obj: CustomObject
override fun onCreate(...){
obj = intent.getExtras().get("key")
// this will init the variable
}
}
lateinit Modifier
57. When to use lateinit
If you’re variable is mutable
If you’re sending a object from another component/
screen — ex Intent extras
lateinit Modifier
58. val myUtil by lazy {
SomeUtil(parameter1, parameter2)
}
Lazy Initialisation
59. val hashMap = HashMap<String, String>()
hashMap.put("keyA", "valueA")
hashMap.put("keyB", "valueB")
hashMap.put("keyC", "valueC")
//change to
val map = mapOf(
"keyA" to "valueA",
"keyB" to "valueB",
"keyC" to "valueC"
)
Kotlin
61. fun parseResponse(response: Response?) =
when (response?.code()) {
null -> throw HTTPException(“Oh no”)
200, 201 -> parse(response.body())
in 400..499 -> throw HTTPException("Invalid request")
in 500..599 -> throw HTTPException("Server error")
else -> throw HTTPException("Error! Code
{response.code()}”)
}
Kotlin
62. Convert .java
Automatic migration might not always result
the best code
//Java
private static final String MY_EXTRA=
"extra_sauce";
//Kotlin
class SomeClass : AppCompatActivity() {
companion object {
}
//Other stuff here
}
private val MY_EXTRA = “extra_sauce”
70. class MyFragment : Fragment(){
companion object {
@JvmStatic
fun newInstance(b:Boolean): MyFragment {
val fragment = MyFragment()
val args = Bundle()
args.putBoolean("isValid",b)
fragment.arguments = args
return fragment
}
Fragments
71. Kotlin
fun handleView() {
for (item in list)
if (item is TextView)
item.text = getString(R.string.play)
else
doRandomOperationOn(item)
}
72. Kotlin
fun handleView() {
list.forEach { item ->
when (item) {
is TextView ->
item.text = getString(R.string.play)
else -> doRandomOperationOn(item)
}
}
}
73. class MyRecyclerAdapter(
val items: List,
val listener: (Item) -> Unit
){
….
}
Kotlin
recycler.adapter = MyRecyclerAdapter(items)
{
navigateToDetail(it)
}
74. fun View.fadeOut(duration: Long = 500):
ViewPropertyAnimator {
return animate()
.alpha(0.0f)
.setDuration(duration)
}
Optional params
icon.fadeOut() // fade out with default time (500)
icon.fadeOut(1000) // fade out with custom time