SlideShare a Scribd company logo
Introduction to Kotlin for
Android App Development
Hardik Trivedi
Hardik Trivedi
● I am a computer program writer
● Works at Globant, Pune, IN
● An active community speaker
● Co-author of an upcoming book "Kotlin Blueprints"
● I love writing tech blogs
● I am mentor for college graduates and professionals and
consultant to companies
About Me
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
What is Kotlin?
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
● Statically typed object oriented language
● Targets JVM, Android and even JavaScript
● Can do anything which Java can.
● Combines Object Oriented and Functional Programming
features.
● But it’s not Functional language.
● Developed and maintained by JetBrains
● Open source
● Released under Apache 2 OSS License
Why Kotlin?
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
Drastically reduce
the amount of
boilerplate code.
Concise
Avoid entire
classes of errors
such as Null
pointer exception
Safe
100% interoperable
with Java. Support
for Android,
Browser and
Native
Interoperable
Excellent tooling
support from
JetBrains
Tool-friendly
Why Kotlin?
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
Drastically reduce
the amount of
boilerplate code.
Concise
Avoid entire
classes of errors
such as Null
pointer exception
Safe
100% interoperable
with Java. Support
for Android,
Browser and
Native
Interoperable
Excellent tooling
support from
JetBrains
Tool-friendly
Why Kotlin?
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
Drastically reduce
the amount of
boilerplate code.
Concise
Avoid entire
classes of errors
such as Null
pointer exception
Safe
100% interoperable
with Java. Support
for Android,
Browser and
Native
Interoperable
Excellent tooling
support from
JetBrains
Tool-friendly
Why Kotlin?
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
Drastically reduce
the amount of
boilerplate code.
Concise
Avoid entire
classes of errors
such as Null
pointer exception
Safe
100% interoperable
with Java. Support
for Android,
Browser and
Native
Interoperable
Excellent tooling
support from
JetBrains
Tool-friendly
Why Kotlin?
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
● Stuck between Java 6 and 7
● No Lambdas, No Streams
● Inability to add methods in platform APIs, have to use Utils
for that
● Loads of NullPointerException
● For Android, it’s Nullability everywhere
● For Android, it loves ceremonies of API
● Need of modern and smart coding language
Kotlin used by industry giants
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
Getting Started
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
● Kotlin is shipped with IntelliJ IDEA 15
● Plugin for Eclipse Luna or greater version. Setup Link
● Try online IDE http://try.kotlinlang.org/
● Android Studio 3.0 is released and Kotlin is by default supported. No other
setup required. Download Android Studio 3.0
● To use Kotlin with the older versions or below Android Studio 3.0, we need to
manually install the latest Kotlin Plugin. Setup Link
Syntax Crash Course
Compile some Kotlin in mind
Object Declaration and Initialization
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
// Immediate assignment
val num: Int = 10
// Implicitly inferred String type
val pName = "Hardik Trivedi"
// Explicit type declaration
var personList:List<String> = ArrayList()
// use underscores to make number constants more readable
val creditCardNumber = 1234_5678_9012_3456L
val vs var
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
// Immutable
“Anything which will not change is val”
// Mutable
“If value will be changed with time use var”
If as expression
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
/* if branches can be blocks, and the last
expression is the value of a block */
val max = if (a > b) {
println("a is greater than b")
a
}
else {
println("a is not greater than b")
b
}
// As expression
val max = if (a > b) a else b
When function
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
// when replaces the switch operator of C, Java-like languages.
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
when (x) {
in 1,2 -> print("X is either 1 or 2")
in validNumbers -> print("x is valid")
in 10..20 -> print("x is inside the range")
else -> print("none of the above")
}
Loops
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
// for loop iterates through anything that provides an iterator.
val list = listOf("Optimus Prime", "Bumblebee", "Ironhide")
// Simple for loop
for (item in list) {
println(item)
}
// De structured
for ((index, value) in list.withIndex()) {
println("the element at $index is $value")
}
Functions
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
//Functions in Kotlin are declared using the fun keyword
fun sum(a: Int, b: Int): Int {
return a + b
}
/*When a function returns a single expression, the curly braces can be omitted and
the body is specified after a = symbol*/
fun sum(a: Int, b: Int, c: Int) = a + b + c
// Function with default argument
fun sum(a: Int, b: Int, c: Int, d: Int = 0) = a + b + c + d
Data classes
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
data class Country(val name: String, val capital: String)
//Code
val india=Country("India","New Delhi")
val norway=Country(capital = "Oslo",name = "Norway")
val (name,capital)=india
println(india.toString())
println(norway.toString())
println("$name ,$capital")
//Output
Country(name=India, capital=New Delhi)
Country(name=Norway, capital=Oslo)
India ,New Delhi
Null Safety
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
No more NullPointerException
Kotlin's type system is aimed to eliminate NullPointerException from our code.
Null Safety
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
/* Now, if you call a method or access a property on a, it's guaranteed not to
cause an NPE, so you can safely say */
val l = a.length
val l = b.length//error: 'b' can be null NOW WHAT TO DO?
Null Safety
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
/* You can explicitly check if b is null, and handle the two options separately */
val l = if (b != null) b.length else -1
//Your second option is the safe call operator, written ?.
val length=b?.length
/* To perform a certain operation only for non-null values, you can use the safe call
operator together with let */
val listWithNulls: List<String?> = listOf("A", null)
for (item in listWithNulls) {
item?.let { println(it) } // prints A and ignores null
}
Extensions
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
// Extension function
fun Date.isTuesday(): Boolean {
return getDay() == 2
}
// Somewhere in code
val date=Date()
println(date.isTuesday())
/* Similarly to functions, Kotlin supports extension properties */
val <T> List<T>.lastIndex: Int
get() = size - 1
Lambdas
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
// Lambdas provides implementation of functional interface (which has single
abstract method-SAM)
button.setOnClickListener(v -> { doSomething() })
// Lambdas other usage
forecastResult.list.forEachIndexed { index, forecast ->
with(forecast) {
println("For index $index value is ${forecast.toString()}")
}
}
Higher order functions
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
● Higher order functions are those which accepts functions as a parameter or
returns the function.
fun Int.perform(other: Int, func: (Int, Int) -> Int): Int {
return func(this, other)
}
// Output
println(10.perform(20, { a, b -> a + b }))
println(10.perform(20) { a, b -> a - b })
println(10.perform(20, { a, b -> a * b }))
println(10.perform(20) { a, b -> a / b })
Lazy or Late
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
● Lazy object gets initialised only while it’s first usage. And will remain always
immutable. It’s a Lambda function.
override val toolbar by lazy { find<Toolbar>(R.id.toolbar) }
● It’s just a late initialisation with non null type. It remains mutable. Used when object is
initialised by Dependency Injection or setUp method of unit test case
lateinit var mockLoanCalculator: LoanCalculator
@Before
public void setUp() throws Exception {
mockLoanCalculator = mock(LoanCalculator::class.java)
}
Let and apply
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
/**
* Calls the specified function [block] with `this` value as its argument and returns
its result.
*/
val result = person.let { it.age * 2 }
/**
* Calls the specified function [block] with `this` value as its receiver and returns
`this` value.
*/
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
}
Wow moments
See Kotlin in Action !!!
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
// Possible only if it's Java 8
public interface InterfaceA {
default void defaultMethod(){
System.out.println("Interface A
default method");
}
}
interface ToolbarManager {
fun initToolbar() {
toolbar.inflateMenu(R.menu.main_menu)
toolbar.setOnMenuItemClickListener {
// Your code
true
}
}
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
private String readInputStream(InputStream is) throws
Exception {
String line = null;
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new
BufferedReader(new InputStreamReader(is));
while ((line = bufferedReader.readLine()) != null)
{
sb.append(line);
}
bufferedReader.close();
return sb.toString();
}
val inputAsString =
is.bufferedReader().use
{ it.readText() }
// defaults to UTF-8
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
Button clickButton = (Button)
findViewById(R.id.clickButton);
clickButton.setOnClickListener( new
OnClickListener() {
@Override
public void onClick(View v) {
***Do what you want with the
click here***
}
});
import
kotlinx.android.synthetic.main.activity_
detail.*
clickButton.setOnClickListener {
***Do what you want with the click
here***
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
button.setVisibility(View.VISIBLE)
button.setVisibility(View.GONE)
fun View.visible() {
this.visibility = View.VISIBLE
}
fun View.gone() {
this.visibility = View.GONE
}
button.visible()
textView.gone()
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
public class MySingleton {
private static MySingleton myObj;
private MySingleton(){
}
public static MySingleton getInstance(){
if(myObj == null){
myObj = new MySingleton();
}
return myObj;
}
}
object MySingleton {
var num: Int = 0
fun domeSomeThing() {
println("Kotlin is awesome!!!")
}
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
SharedPreferences sharedpreferences =
getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
email.setText(sharedpreferences.getStrin
g(Email, ""));
SharedPreferences.Editor editor =
sharedpreferences.edit();
editor.putString("email",
"trivedi.hardik.11@gmail.com");
editor.apply();
private var email: String by
DelegatedPreference(this, "email", "")
email="trivedi.hardik.11@gmail.com"
txtEmail.text=email
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
Movie movie = moviesList.get(position);
holder.title.setText(movie.getTitle());
holder.genre.setText(movie.getGenre());
holder.year.setText(movie.getYear());
Movie movie = moviesList[position]
with(movie) {
holder.title.text=title
holder.genre.text=genre
holder.year.text=year
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
private class GetWeatherTask extends
AsyncTask<String, Void, Forecast> {
protected Forecast doInBackground(String
zipCode) {
return WeatherAPI().execute(zipCode);
}
protected void onPostExecute(Forecast
result) {
showData(result);
}
}
new GetWeatherTask().execute(380015);
fun loadWeatherData() = async(UI) {
val waiter = bg {
WeatherApi(zipCode).execute() }
showData(waiter.await())
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
Intent intent = Intent(this,BActivity.class)
intent.putExtra("id", 5)
intent.setFlag(Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
startActivity(intentFor<SomeOtherActivity>("id" to 5).singleTop())
Java
Kotlin
Smart Cast
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
// Java style
if (obj instanceof TextArea) {
((TextArea)obj).append("some data");
} else {
// Do something
}
// Kotlin does it smartly
if (view is TextArea) {
view.append("Kotlin is awesome!")
} else {
// Do something
}
Anko - Android’s buddy for Kotlin
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
textView {
id = R.id.errorView
textColor = ContextCompat.getColor(ctx, R.color.red_error)
text = string(R.string.error_view_login_text)
textSize = 14f
visibility = View.GONE
}
textView {
lparams(width = matchParent, height = wrapContent) {
gravity = Gravity.CENTER
leftMargin = dip(16)
rightMargin = dip(16)
}
}
Anko - Android’s buddy for Kotlin
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
// Showing Alerts
alert("Hi, are you enjoying the Kotlin talk?") {
yesButton { toast("Yes :)") }
noButton {}
}.show()
// Showing progress dialog
val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")
// Showing SnackBar
snackbar(view, "Hi there!")
snackbar(view, R.string.message)
longSnackbar(view, "Wow, such duration")
snackbar(view, "Action, reaction", "Click me!") { doStuff() }
There is more to come than meets the eye
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
● Visibility Modifiers
● Companion Objects
● Nested, Sealed classes
● Generics
● Coroutines
● Operator Overloading
● Exceptions
● Annotations
● Reflection
● And Many more...
Improvement areas for Kotlin
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
● Increased build time by few seconds
● Adds approx 6K more methods in final package
● No static analysers, but same can be achieved using companion objects
● Mocking kotlin classes with Mockito is painful
● Operator overloading may lead to bad result if not used properly
● Smaller community and less available help
● Might be difficult to code in functional paradigm
Future of Kotlin
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
JVM Native
iOS, etc.
JS
Kotlin
Android Spring, etc.
References
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
● Official Website
● Git repo from Developer Advocate at JetBrains
● Kotlin vs Java build comparison
● Android Development with Kotlin - Jake Wharton
● Antonio Leiva's Blog
● Anko Github page
● Sample Android app using Kotlin
End note
Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
when (Talk.STATUS) {
TALK_ENDS -> println("Let's discuss Queries")
NO_QUERIES -> println("Thank you :)")
}
Thank You
trivedi.hardik.11@gmail.com
https://trivedihardik.wordpress.com
@11Trivedi

More Related Content

PPTX
Introduction to Koltin for Android Part I
PPSX
Kotlin Language powerpoint show file
PPTX
Android Development with Kotlin course
PDF
Introduction to kotlin
PDF
Android Development with Kotlin, Part 1 - Introduction
PPTX
Android Intent.pptx
ZIP
Android Application Development
Introduction to Koltin for Android Part I
Kotlin Language powerpoint show file
Android Development with Kotlin course
Introduction to kotlin
Android Development with Kotlin, Part 1 - Introduction
Android Intent.pptx
Android Application Development

What's hot (20)

PDF
Kotlin for Android Development
PDF
Data Persistence in Android with Room Library
PPTX
Kotlin on android
PPTX
Android jetpack compose | Declarative UI
PDF
PPT
The Kotlin Programming Language
PDF
A quick and fast intro to Kotlin
PPTX
Introduction to Node js
PDF
Declarative UIs with Jetpack Compose
PPTX
Kotlin as a Better Java
PPT
TypeScript Presentation
PDF
Java SE 8 best practices
PDF
Express node js
PPTX
Kotlin Basics & Introduction to Jetpack Compose.pptx
PDF
What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...
PPTX
Kotlin InDepth Tutorial for beginners 2022
PPT
PPTX
Introduction to kotlin and OOP in Kotlin
PPTX
React js
PPTX
Coroutines in Kotlin
Kotlin for Android Development
Data Persistence in Android with Room Library
Kotlin on android
Android jetpack compose | Declarative UI
The Kotlin Programming Language
A quick and fast intro to Kotlin
Introduction to Node js
Declarative UIs with Jetpack Compose
Kotlin as a Better Java
TypeScript Presentation
Java SE 8 best practices
Express node js
Kotlin Basics & Introduction to Jetpack Compose.pptx
What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...
Kotlin InDepth Tutorial for beginners 2022
Introduction to kotlin and OOP in Kotlin
React js
Coroutines in Kotlin
Ad

Similar to Introduction to kotlin for android app development gdg ahmedabad dev fest 2017 (20)

PDF
Getting Started With Kotlin Development - Rivu
PDF
Privet Kotlin (Windy City DevFest)
PDF
Kotlin: A pragmatic language by JetBrains
PDF
Kotlin a problem solver - gdd extended pune
PDF
Kotlin for Android devs
PPTX
Exploring Kotlin language basics for Android App development
PDF
Kotlin what_you_need_to_know-converted event 4 with nigerians
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
PDF
Kotlin Introduction with Android applications
PPTX
Intro to kotlin 2018
PDF
Practical tips for building apps with kotlin
PDF
Kotlin, smarter development for the jvm
PDF
PDF
First few months with Kotlin - Introduction through android examples
PDF
Save time with kotlin in android development
PPTX
Kotlin : Happy Development
PDF
Exploring Kotlin
PDF
Kotlin for Android Developers - 3
PPTX
Building Mobile Apps with Android
PDF
Intro to Kotlin
Getting Started With Kotlin Development - Rivu
Privet Kotlin (Windy City DevFest)
Kotlin: A pragmatic language by JetBrains
Kotlin a problem solver - gdd extended pune
Kotlin for Android devs
Exploring Kotlin language basics for Android App development
Kotlin what_you_need_to_know-converted event 4 with nigerians
Develop your next app with kotlin @ AndroidMakersFr 2017
Kotlin Introduction with Android applications
Intro to kotlin 2018
Practical tips for building apps with kotlin
Kotlin, smarter development for the jvm
First few months with Kotlin - Introduction through android examples
Save time with kotlin in android development
Kotlin : Happy Development
Exploring Kotlin
Kotlin for Android Developers - 3
Building Mobile Apps with Android
Intro to Kotlin
Ad

Recently uploaded (20)

PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Encapsulation theory and applications.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Machine Learning_overview_presentation.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
1. Introduction to Computer Programming.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Empathic Computing: Creating Shared Understanding
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Approach and Philosophy of On baking technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
A Presentation on Artificial Intelligence
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Per capita expenditure prediction using model stacking based on satellite ima...
Encapsulation theory and applications.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Machine Learning_overview_presentation.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Mobile App Security Testing_ A Comprehensive Guide.pdf
1. Introduction to Computer Programming.pptx
Network Security Unit 5.pdf for BCA BBA.
A comparative analysis of optical character recognition models for extracting...
Empathic Computing: Creating Shared Understanding
Unlocking AI with Model Context Protocol (MCP)
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
Approach and Philosophy of On baking technology
“AI and Expert System Decision Support & Business Intelligence Systems”
Assigned Numbers - 2025 - Bluetooth® Document
A Presentation on Artificial Intelligence

Introduction to kotlin for android app development gdg ahmedabad dev fest 2017

  • 1. Introduction to Kotlin for Android App Development Hardik Trivedi
  • 2. Hardik Trivedi ● I am a computer program writer ● Works at Globant, Pune, IN ● An active community speaker ● Co-author of an upcoming book "Kotlin Blueprints" ● I love writing tech blogs ● I am mentor for college graduates and professionals and consultant to companies About Me Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com
  • 3. What is Kotlin? Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com ● Statically typed object oriented language ● Targets JVM, Android and even JavaScript ● Can do anything which Java can. ● Combines Object Oriented and Functional Programming features. ● But it’s not Functional language. ● Developed and maintained by JetBrains ● Open source ● Released under Apache 2 OSS License
  • 4. Why Kotlin? Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com Drastically reduce the amount of boilerplate code. Concise Avoid entire classes of errors such as Null pointer exception Safe 100% interoperable with Java. Support for Android, Browser and Native Interoperable Excellent tooling support from JetBrains Tool-friendly
  • 5. Why Kotlin? Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com Drastically reduce the amount of boilerplate code. Concise Avoid entire classes of errors such as Null pointer exception Safe 100% interoperable with Java. Support for Android, Browser and Native Interoperable Excellent tooling support from JetBrains Tool-friendly
  • 6. Why Kotlin? Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com Drastically reduce the amount of boilerplate code. Concise Avoid entire classes of errors such as Null pointer exception Safe 100% interoperable with Java. Support for Android, Browser and Native Interoperable Excellent tooling support from JetBrains Tool-friendly
  • 7. Why Kotlin? Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com Drastically reduce the amount of boilerplate code. Concise Avoid entire classes of errors such as Null pointer exception Safe 100% interoperable with Java. Support for Android, Browser and Native Interoperable Excellent tooling support from JetBrains Tool-friendly
  • 8. Why Kotlin? Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com ● Stuck between Java 6 and 7 ● No Lambdas, No Streams ● Inability to add methods in platform APIs, have to use Utils for that ● Loads of NullPointerException ● For Android, it’s Nullability everywhere ● For Android, it loves ceremonies of API ● Need of modern and smart coding language
  • 9. Kotlin used by industry giants Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com
  • 10. Getting Started Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com ● Kotlin is shipped with IntelliJ IDEA 15 ● Plugin for Eclipse Luna or greater version. Setup Link ● Try online IDE http://try.kotlinlang.org/ ● Android Studio 3.0 is released and Kotlin is by default supported. No other setup required. Download Android Studio 3.0 ● To use Kotlin with the older versions or below Android Studio 3.0, we need to manually install the latest Kotlin Plugin. Setup Link
  • 11. Syntax Crash Course Compile some Kotlin in mind
  • 12. Object Declaration and Initialization Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com // Immediate assignment val num: Int = 10 // Implicitly inferred String type val pName = "Hardik Trivedi" // Explicit type declaration var personList:List<String> = ArrayList() // use underscores to make number constants more readable val creditCardNumber = 1234_5678_9012_3456L
  • 13. val vs var Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com // Immutable “Anything which will not change is val” // Mutable “If value will be changed with time use var”
  • 14. If as expression Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com /* if branches can be blocks, and the last expression is the value of a block */ val max = if (a > b) { println("a is greater than b") a } else { println("a is not greater than b") b } // As expression val max = if (a > b) a else b
  • 15. When function Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com // when replaces the switch operator of C, Java-like languages. when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { // Note the block print("x is neither 1 nor 2") } } when (x) { in 1,2 -> print("X is either 1 or 2") in validNumbers -> print("x is valid") in 10..20 -> print("x is inside the range") else -> print("none of the above") }
  • 16. Loops Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com // for loop iterates through anything that provides an iterator. val list = listOf("Optimus Prime", "Bumblebee", "Ironhide") // Simple for loop for (item in list) { println(item) } // De structured for ((index, value) in list.withIndex()) { println("the element at $index is $value") }
  • 17. Functions Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com //Functions in Kotlin are declared using the fun keyword fun sum(a: Int, b: Int): Int { return a + b } /*When a function returns a single expression, the curly braces can be omitted and the body is specified after a = symbol*/ fun sum(a: Int, b: Int, c: Int) = a + b + c // Function with default argument fun sum(a: Int, b: Int, c: Int, d: Int = 0) = a + b + c + d
  • 18. Data classes Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com data class Country(val name: String, val capital: String) //Code val india=Country("India","New Delhi") val norway=Country(capital = "Oslo",name = "Norway") val (name,capital)=india println(india.toString()) println(norway.toString()) println("$name ,$capital") //Output Country(name=India, capital=New Delhi) Country(name=Norway, capital=Oslo) India ,New Delhi
  • 19. Null Safety Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com No more NullPointerException Kotlin's type system is aimed to eliminate NullPointerException from our code.
  • 20. Null Safety Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com var a: String = "abc" a = null // compilation error var b: String? = "abc" b = null // ok /* Now, if you call a method or access a property on a, it's guaranteed not to cause an NPE, so you can safely say */ val l = a.length val l = b.length//error: 'b' can be null NOW WHAT TO DO?
  • 21. Null Safety Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com /* You can explicitly check if b is null, and handle the two options separately */ val l = if (b != null) b.length else -1 //Your second option is the safe call operator, written ?. val length=b?.length /* To perform a certain operation only for non-null values, you can use the safe call operator together with let */ val listWithNulls: List<String?> = listOf("A", null) for (item in listWithNulls) { item?.let { println(it) } // prints A and ignores null }
  • 22. Extensions Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com // Extension function fun Date.isTuesday(): Boolean { return getDay() == 2 } // Somewhere in code val date=Date() println(date.isTuesday()) /* Similarly to functions, Kotlin supports extension properties */ val <T> List<T>.lastIndex: Int get() = size - 1
  • 23. Lambdas Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com // Lambdas provides implementation of functional interface (which has single abstract method-SAM) button.setOnClickListener(v -> { doSomething() }) // Lambdas other usage forecastResult.list.forEachIndexed { index, forecast -> with(forecast) { println("For index $index value is ${forecast.toString()}") } }
  • 24. Higher order functions Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com ● Higher order functions are those which accepts functions as a parameter or returns the function. fun Int.perform(other: Int, func: (Int, Int) -> Int): Int { return func(this, other) } // Output println(10.perform(20, { a, b -> a + b })) println(10.perform(20) { a, b -> a - b }) println(10.perform(20, { a, b -> a * b })) println(10.perform(20) { a, b -> a / b })
  • 25. Lazy or Late Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com ● Lazy object gets initialised only while it’s first usage. And will remain always immutable. It’s a Lambda function. override val toolbar by lazy { find<Toolbar>(R.id.toolbar) } ● It’s just a late initialisation with non null type. It remains mutable. Used when object is initialised by Dependency Injection or setUp method of unit test case lateinit var mockLoanCalculator: LoanCalculator @Before public void setUp() throws Exception { mockLoanCalculator = mock(LoanCalculator::class.java) }
  • 26. Let and apply Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com /** * Calls the specified function [block] with `this` value as its argument and returns its result. */ val result = person.let { it.age * 2 } /** * Calls the specified function [block] with `this` value as its receiver and returns `this` value. */ supportActionBar?.apply { setDisplayHomeAsUpEnabled(true) setDisplayShowHomeEnabled(true) }
  • 27. Wow moments See Kotlin in Action !!!
  • 28. Wow moments Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com // Possible only if it's Java 8 public interface InterfaceA { default void defaultMethod(){ System.out.println("Interface A default method"); } } interface ToolbarManager { fun initToolbar() { toolbar.inflateMenu(R.menu.main_menu) toolbar.setOnMenuItemClickListener { // Your code true } } } Java Kotlin
  • 29. Wow moments Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com private String readInputStream(InputStream is) throws Exception { String line = null; StringBuilder sb = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); while ((line = bufferedReader.readLine()) != null) { sb.append(line); } bufferedReader.close(); return sb.toString(); } val inputAsString = is.bufferedReader().use { it.readText() } // defaults to UTF-8 Java Kotlin
  • 30. Wow moments Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com Button clickButton = (Button) findViewById(R.id.clickButton); clickButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { ***Do what you want with the click here*** } }); import kotlinx.android.synthetic.main.activity_ detail.* clickButton.setOnClickListener { ***Do what you want with the click here*** } Java Kotlin
  • 31. Wow moments Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com button.setVisibility(View.VISIBLE) button.setVisibility(View.GONE) fun View.visible() { this.visibility = View.VISIBLE } fun View.gone() { this.visibility = View.GONE } button.visible() textView.gone() Java Kotlin
  • 32. Wow moments Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com public class MySingleton { private static MySingleton myObj; private MySingleton(){ } public static MySingleton getInstance(){ if(myObj == null){ myObj = new MySingleton(); } return myObj; } } object MySingleton { var num: Int = 0 fun domeSomeThing() { println("Kotlin is awesome!!!") } } Java Kotlin
  • 33. Wow moments Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com SharedPreferences sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE); email.setText(sharedpreferences.getStrin g(Email, "")); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString("email", "[email protected]"); editor.apply(); private var email: String by DelegatedPreference(this, "email", "") email="[email protected]" txtEmail.text=email Java Kotlin
  • 34. Wow moments Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com Movie movie = moviesList.get(position); holder.title.setText(movie.getTitle()); holder.genre.setText(movie.getGenre()); holder.year.setText(movie.getYear()); Movie movie = moviesList[position] with(movie) { holder.title.text=title holder.genre.text=genre holder.year.text=year } Java Kotlin
  • 35. Wow moments Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com private class GetWeatherTask extends AsyncTask<String, Void, Forecast> { protected Forecast doInBackground(String zipCode) { return WeatherAPI().execute(zipCode); } protected void onPostExecute(Forecast result) { showData(result); } } new GetWeatherTask().execute(380015); fun loadWeatherData() = async(UI) { val waiter = bg { WeatherApi(zipCode).execute() } showData(waiter.await()) } Java Kotlin
  • 36. Wow moments Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com Intent intent = Intent(this,BActivity.class) intent.putExtra("id", 5) intent.setFlag(Intent.FLAG_ACTIVITY_SINGLE_TOP) startActivity(intent) startActivity(intentFor<SomeOtherActivity>("id" to 5).singleTop()) Java Kotlin
  • 37. Smart Cast Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com // Java style if (obj instanceof TextArea) { ((TextArea)obj).append("some data"); } else { // Do something } // Kotlin does it smartly if (view is TextArea) { view.append("Kotlin is awesome!") } else { // Do something }
  • 38. Anko - Android’s buddy for Kotlin Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com textView { id = R.id.errorView textColor = ContextCompat.getColor(ctx, R.color.red_error) text = string(R.string.error_view_login_text) textSize = 14f visibility = View.GONE } textView { lparams(width = matchParent, height = wrapContent) { gravity = Gravity.CENTER leftMargin = dip(16) rightMargin = dip(16) } }
  • 39. Anko - Android’s buddy for Kotlin Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com // Showing Alerts alert("Hi, are you enjoying the Kotlin talk?") { yesButton { toast("Yes :)") } noButton {} }.show() // Showing progress dialog val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data") // Showing SnackBar snackbar(view, "Hi there!") snackbar(view, R.string.message) longSnackbar(view, "Wow, such duration") snackbar(view, "Action, reaction", "Click me!") { doStuff() }
  • 40. There is more to come than meets the eye Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com ● Visibility Modifiers ● Companion Objects ● Nested, Sealed classes ● Generics ● Coroutines ● Operator Overloading ● Exceptions ● Annotations ● Reflection ● And Many more...
  • 41. Improvement areas for Kotlin Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com ● Increased build time by few seconds ● Adds approx 6K more methods in final package ● No static analysers, but same can be achieved using companion objects ● Mocking kotlin classes with Mockito is painful ● Operator overloading may lead to bad result if not used properly ● Smaller community and less available help ● Might be difficult to code in functional paradigm
  • 42. Future of Kotlin Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com JVM Native iOS, etc. JS Kotlin Android Spring, etc.
  • 43. References Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com ● Official Website ● Git repo from Developer Advocate at JetBrains ● Kotlin vs Java build comparison ● Android Development with Kotlin - Jake Wharton ● Antonio Leiva's Blog ● Anko Github page ● Sample Android app using Kotlin
  • 44. End note Email: [email protected] Follow: @11Trivedi Visit: trivedihardik.wordpress.com when (Talk.STATUS) { TALK_ENDS -> println("Let's discuss Queries") NO_QUERIES -> println("Thank you :)") }