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
PPTX
Android Development with Kotlin course
PPSX
Kotlin Language powerpoint show file
PDF
Introduction to kotlin
PDF
Android Development with Kotlin, Part 1 - Introduction
PPTX
Android Intent.pptx
PPT
Unit I Advanced Java Programming Course
Introduction to Koltin for Android Part I
Android Development with Kotlin course
Kotlin Language powerpoint show file
Introduction to kotlin
Android Development with Kotlin, Part 1 - Introduction
Android Intent.pptx
Unit I Advanced Java Programming Course

What's hot (20)

PDF
Kotlin for Android Development
PDF
A quick and fast intro to Kotlin
PPT
The Kotlin Programming Language
PPTX
Broadcast Receiver
PPTX
Kotlin presentation
PDF
Declarative UIs with Jetpack Compose
PDF
Android Jetpack Compose - Turkey 2021
PPTX
Android with kotlin course
PPTX
Jetpack Compose.pptx
PDF
Try Jetpack Compose
PDF
Introduction to Kotlin coroutines
PPTX
Introduction to Kotlin Language and its application to Android platform
PPT
SQLITE Android
PPTX
Android jetpack compose | Declarative UI
PPTX
Kotlin on android
PPTX
Introduction to kotlin and OOP in Kotlin
PDF
Jetpack compose
PDF
Kotlin - Better Java
PDF
Jetpack Compose beginner.pdf
PPT
Core java concepts
Kotlin for Android Development
A quick and fast intro to Kotlin
The Kotlin Programming Language
Broadcast Receiver
Kotlin presentation
Declarative UIs with Jetpack Compose
Android Jetpack Compose - Turkey 2021
Android with kotlin course
Jetpack Compose.pptx
Try Jetpack Compose
Introduction to Kotlin coroutines
Introduction to Kotlin Language and its application to Android platform
SQLITE Android
Android jetpack compose | Declarative UI
Kotlin on android
Introduction to kotlin and OOP in Kotlin
Jetpack compose
Kotlin - Better Java
Jetpack Compose beginner.pdf
Core java concepts
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
PPTX
Kotlin as a Better Java
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
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
Kotlin as a Better Java
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
Ad

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Cloud computing and distributed systems.
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPT
Teaching material agriculture food technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Encapsulation_ Review paper, used for researhc scholars
Digital-Transformation-Roadmap-for-Companies.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Review of recent advances in non-invasive hemoglobin estimation
Cloud computing and distributed systems.
The AUB Centre for AI in Media Proposal.docx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Teaching material agriculture food technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
MYSQL Presentation for SQL database connectivity
Spectral efficient network and resource selection model in 5G networks
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Reach Out and Touch Someone: Haptics and Empathic Computing
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced methodologies resolving dimensionality complications for autism neur...
Chapter 3 Spatial Domain Image Processing.pdf

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: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
  • 3. 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
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. Kotlin used by industry giants Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com
  • 10. 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
  • 11. Syntax Crash Course Compile some Kotlin in mind
  • 12. 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
  • 13. 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”
  • 14. 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
  • 15. 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") }
  • 16. 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") }
  • 17. 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
  • 18. 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
  • 19. 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.
  • 20. 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?
  • 21. 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 }
  • 22. 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
  • 23. 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()}") } }
  • 24. 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 })
  • 25. 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) }
  • 26. 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) }
  • 27. Wow moments See Kotlin in Action !!!
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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 }
  • 38. 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) } }
  • 39. 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() }
  • 40. 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...
  • 41. 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
  • 42. Future of Kotlin Email: trivedi.hardik.11@gmail.com Follow: @11Trivedi Visit: trivedihardik.wordpress.com JVM Native iOS, etc. JS Kotlin Android Spring, etc.
  • 43. 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
  • 44. 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 :)") }