SlideShare a Scribd company logo
Delightul hacking
with Kotlin
Klemen Kresnik
developer @
Kotlin?
• Designed and developed by JetBrains
• Statically-typed programming language
• Compiles to JVM bytecode, runs on JVM
• v1.0 released on February 16, 2016
• Latest version 1.0.2 (Android Lint
Checks, method count reduced ~1500)
Main features
• Null safety
• Functions
• Sequences
• Extensions
• Data classes
Other sugars
• String templates
• ‘when' expression
• Smart casts
• Kotlin from Java - @JvmOverloads
Kotlin & Android
• Install Kotlin IDEA plugin
• Enable Kotlin Android plugin
• Enable Kotlin Android Extensions
plugin
• Add stdlib dependency
Setup with AS
Install IDEA Kotlin plugin
Add Kotlin plugin to build.gradle
buildscript {

ext.kotlin_version = ‘<kotlin_version>'

repositories {

mavenCentral()

}

dependencies {

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

}

}

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'
android {

...

sourceSets {

main.java.srcDirs += 'src/main/kotlin'

}

}
dependencies {

...

compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

}
Kotlin Android Extensions
• Part of Kotlin IDEA plugin
• View binder library similar to
Butterknife
• Plugin for the Kotlin compiler
• Based on extensions properties
Add Kotlin Android Extensions plugin to
build.gradle
apply plugin: 'kotlin-android-extensions'
Usage
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/container"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"/>
Without extensions
findViewById(R.id.container)?.visibility = View.INVISIBLE
With extensions
import kotlinx.android.synthetic.main.activity_delightful.*
container.visibility = View.INVISIBLE

Null safety
• Aims to eliminate NPE danger in code
• NPE can be thrown explicitly or by
usage of !! operator (for NPE lovers
:))
• By default references cannot be null
• Allow null with ? operator
Do not allow null values
data class Clip(val title: String)
data class FeedPost(var clip: Clip)
var data = FeedPost(Clip(null)) //Won't compile
Allow null values
data class Clip(val title: String?)
data class FeedPost(var clip: Clip?)
var data = FeedPost(Clip(null)) //Will compile
Results to
var data:FeedPost? = fetchFromBackend()
//Some code that maybe sets data reference

textView.text = (data?.clip?.title)
Java
if(data != null && data.clip != null && data.clip.title != null) {

//Code that uses data

}
What about this?
fun setText(title:String) {

}
setText(data?.clip?.title!!)
Functions
• Top level functions support
• Default Arguments
• Named Arguments
• Higher-Order Functions and Lambdas
• Inline functions
• Extension Functions
Default arguments
Java
private void setData(List<Clip> clipList, Set<String> ids, boolean reset) {

...

}
Kotlin
private fun setData(clipList: List<Clip>, ids: Set<String> = emptySet<String>(),
reset: Boolean = false) {
...
}
setData(loadedDataFromBackend, emptySet(), true)


setData(loadedDataFromBackend)
Named arguments
Let’s add a few more parameters to
setData function
Java
private void setData(List<Clip> clipList, Set<String> ids, boolean reset, boolean orderDescending,
boolean skipViewed) {

}
setData(loadedDataFromBackend, new HashSet<String>(), false, true, false);
Kotlin
private fun setData(clipList: List<Clip>, ids: Set<String> = emptySet(), reset: Boolean = false,

orderDescending: Boolean = false, skipViewed: Boolean = false) {

}
setData(clipList = emptyList(), reset = true, skipViewed = false, orderDescending = true)
Higher-Order Functions
and Lambdas
• A higher-order function takes
functions as parameter, or returns a
function
• A lambda expression or an anonymous
function is a function that is not
declared, but passed immediately as
an expression
Lambda syntax for MenuItemClickListener
var menuItemClickListenerLambdaFunction: (MenuItem) -> Boolean = { menuItem -> true }
Concise version
var menuItemClickListenerLambdaFunction = { menuItem: MenuItem ->

if (menuItem.itemId == R.id.menu_settings) {

true

}

false

}
MenuItemClickListener in Java
OnMenuItemClickListener onMenuItemClickListener = new Toolbar.OnMenuItemClickListener() {

@Override

public boolean onMenuItemClick(MenuItem item) {

return false;

}

};
Compared to lambdas in Java
• Retrolambda (replaces lambdas with
anonymous class through bytecode
manipulation)
• Compile with Android N (lambda is
compiled into class with constructor
and method)
• Increasing method count and creating
pressure on GC
• Kotlin generates bytecode from
lambdas using inline functions
Sequences
• Inside kotlin.sequences
• Similar to Java 8 Streams API
• Implemented as extension functions
• zip, map, reduce, filter etc…
Suppose we have a collection of video clips, where
each clip has an id. We would like to store ids of
clips where the title length is less than 10
characters in a separate collection
Java
for(Clip item : items) {

if(item.getTitle().length() < 10) {

ids.add(item.getId());

}

}
Kotlin
items.map { it -> it.id }.filter { it -> it.length < 10 }.forEach { it -> ids.add(it) }
items.map { it.id }.filter { it.length < 10 }.forEach { ids.add(it) }
In Java?
• Streams API in Java 8 with Android N
• RxJava
Extensions
• Add functionality to a class without
extending it
• Support through extension functions
and extension properties
• Get rid of StringUtils, ViewUtils
classes
Extension properties
val <Context> Context.context: android.content.Context?

get() = getApplicationContext()
val <Activity> Activity.view_pager: android.support.v4.view.ViewPager?

get() = findViewById(R.id.view_pager) as android.support.v4.view.ViewPager?
• Prefix function name with class name
that we are extending
• All class methods and fields are
available inside the extension
function
• No actual classes are modified.
Functions are callable with the dot-
notation on instances of this class
Extension Functions
Example 1
Java
public static float convertDpToPixel(Context context, float dp){

Resources resources = context.getResources();

DisplayMetrics metrics = resources.getDisplayMetrics();

return dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);

}
Kotlin
fun Context.dpToPx(dp: Float): Int {

val resources = this.resources

val metrics = resources.displayMetrics

return (dp * (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)).toInt()

}
//Inside Activity

val dp = dpToPx(6f)
Example 2
Java
Context context = getApplicationContext();

Drawable tintedDrawable = DrawableCompat.wrap(ContextCompat.getDrawable(context, R.drawable.ic_arrow));

DrawableCompat.setTint(tintedDrawable, ContextCompat.getColor(context, R.color.colorAccentDark));

DrawableCompat.unwrap(tintedDrawable);
Kotlin
fun Drawable.tint(context: Context,

@ColorRes color: Int): Drawable {

val tintedDrawable = DrawableCompat.wrap(this)

DrawableCompat.setTint(tintedDrawable, ContextCompat.getColor(context, color))

DrawableCompat.unwrap<Drawable>(this)

return tintedDrawable

}
ContextCompat.getDrawable(applicationContext, R.drawable.ic_arrow).tint(applicationContext,
R.color.colorAccentDark)
More complex example
fun ImageView.loadUrl(path: String?,

transformation: RequestCreator.() -> RequestCreator = { this }) =

Picasso.with(context).load(path).transformation().into(this)
thumbnailView.loadUrl(thumbnailUrl) {

transform(RoundedCornersTransformation(

thumbnailView.context.dpToPx(4f), 0

)).fit()

}
• loadUrl function takes functions as a
second parameter
• when calling loadUrl function we pass
a function that will be invoked
Data classes
• Intented to hold data
• Auto generated equals(), hashCode(),
toString() and copy()
• At least one parameter in
constructor
• Can’t be abstract
• Can implement, can’t extend…for now
Example
data class Clip(val id: String, val title: String)
@PaperParcel

data class Clip(val id: String, val title: String) : PaperParcelable {

companion object {

@JvmField val CREATOR = PaperParcelable.Creator(Clip::class.java)

}

}
with Parcelable
Other sugars
String templates
private fun setData(clipList: List<Clip>, ids: Set<String> = emptySet(), reset: Boolean = false,

orderDescending: Boolean = false, skipViewed: Boolean = false) {

Timber.i("Log parameters number of clip:${clipList.size} orderDescending:$orderDescending ")

}
When expression
Create view holder
Java
@Override

public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

switch (viewType) {

case VIEW_TYPE_ONE:

return new ViewHolderOne(LayoutInflater

.from(parent.getContext())

.inflate(R.layout.item_layout_one, parent, false));



case VIEW_TYPE_TWO:

return new ViewHolderTwo(LayoutInflater

.from(parent.getContext())

.inflate(R.layout.item_layout_two, parent, false));



case VIEW_TYPE_THREE:

return new ViewHolderThree(LayoutInflater

.from(parent.getContext())

.inflate(R.layout.item_layout_three, parent, false));



default:

throw new RuntimeException();

}

}
Kotlin
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) {

VIEW_TYPE_ONE -> ViewHolderOne(parent.inflate<View>(R.layout.item_layout_one))

VIEW_TYPE_TWO -> ViewHolderTwo(parent.inflate<View>(R.layout.item_layout_two))

VIEW_TYPE_THREE -> ViewHolderThree(parent.inflate<View>(R.layout.item_layout_three))

else -> throw RuntimeException("Invalid view type.")

}

Smart casts
• Cast by using is or !is operator
• Compiler tracks is-checks for
immutable values and inserts casts
automatically
Java
@Override

public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

if (holder instanceof ViewHolderOne) {

ViewHolderOne holderOne = (ViewHolderOne) holder;

} else if (holder instanceof ViewHolderTwo) {

ViewHolderTwo holderTwo = (ViewHolderTwo) holder;

} else if (holder instanceof ViewHolderThree) {

ViewHolderThree holderThree = (ViewHolderThree) holder;

}

}
Example with binding view holder
Kotlin
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

if (holder is ViewHolderOne) {

val holderOne:ViewHolderOne = holder

} else if (holder is ViewHolderTwo) {

val holder:TwoViewHolderTwo = holder

} else if (holder is ViewHolderThree) {

val holder:ThreeViewHolderThree = holder

}

}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) = when(holder){

is ClipAdapter.ViewHolderOne -> ...

is ClipAdapter.ViewHolderTwo -> ...

is ClipAdapter.ViewHolderThree -> ...

}
or even better
@JvmOverloads
• Call Kotlin from Java
• Provide all versions of constructor
Example by extending a view
class ActivityView(context: Context, 

attrs: AttributeSet? = null, 

defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr){



constructor(context: Context):this(context, null, -1) {

}

constructor(context: Context, attrs: AttributeSet? ):this(context, attrs, -1) {

}
}
class ActivityView : RelativeLayout {

@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)

: super(context, attrs, defStyleAttr)
}
Future is bright
• Gradle scripting in Kotlin
• Incremental compilation
• Data class inheritance support
• Java 8/9 support
• Jack & Jill toolchain integration
Any apps out there?
• Expedia Hotels, Flights & Cars
• BlueCrew
• Level Money
• LifeHack Chisinau
• Changelogs
I want more
• http://antonioleiva.com/kotlin/
• https://kotlinlang.org/docs/
reference/
• http://kotlinlang.slack.com/
Questions?
Thanks
Code Android with joy. Try Kotlin.

More Related Content

What's hot

Scala introduction
Scala introductionScala introduction
Scala introduction
Yardena Meymann
 
Demystifying Oak Search
Demystifying Oak SearchDemystifying Oak Search
Demystifying Oak Search
Justin Edelson
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
Yardena Meymann
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
intelliyole
 
All about scala
All about scalaAll about scala
All about scala
Yardena Meymann
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentation
Gene Chang
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Connect 2016-Move Your XPages Applications to the Fast Lane
Connect 2016-Move Your XPages Applications to the Fast LaneConnect 2016-Move Your XPages Applications to the Fast Lane
Connect 2016-Move Your XPages Applications to the Fast Lane
Howard Greenberg
 
BASTA 2013: Custom OData Provider
BASTA 2013: Custom OData ProviderBASTA 2013: Custom OData Provider
BASTA 2013: Custom OData Provider
Rainer Stropek
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
Boulder Java User's Group
 
Python在豆瓣的应用
Python在豆瓣的应用Python在豆瓣的应用
Python在豆瓣的应用
Qiangning Hong
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
Alex Payne
 
Polyglot Grails
Polyglot GrailsPolyglot Grails
Polyglot Grails
Marcin Gryszko
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Garth Gilmour
 
XML-Motor
XML-MotorXML-Motor
XML-Motor
Abhishek Kumar
 
Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverDataStax Academy
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling Rewriter
Justin Edelson
 
Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM  Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM
Mark Rees
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
Felipe
 

What's hot (20)

Scala introduction
Scala introductionScala introduction
Scala introduction
 
Demystifying Oak Search
Demystifying Oak SearchDemystifying Oak Search
Demystifying Oak Search
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
All about scala
All about scalaAll about scala
All about scala
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentation
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Connect 2016-Move Your XPages Applications to the Fast Lane
Connect 2016-Move Your XPages Applications to the Fast LaneConnect 2016-Move Your XPages Applications to the Fast Lane
Connect 2016-Move Your XPages Applications to the Fast Lane
 
BASTA 2013: Custom OData Provider
BASTA 2013: Custom OData ProviderBASTA 2013: Custom OData Provider
BASTA 2013: Custom OData Provider
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
Python在豆瓣的应用
Python在豆瓣的应用Python在豆瓣的应用
Python在豆瓣的应用
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Polyglot Grails
Polyglot GrailsPolyglot Grails
Polyglot Grails
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
 
XML-Motor
XML-MotorXML-Motor
XML-Motor
 
Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling Rewriter
 
Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM  Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 

Viewers also liked

C7 Victim rights’ and the right to a fair trial
C7 Victim rights’ and the right to a fair trialC7 Victim rights’ and the right to a fair trial
C7 Victim rights’ and the right to a fair trial
VSE 2016
 
B7 Privacy true the eyes of the victim
B7 Privacy true the eyes of the victimB7 Privacy true the eyes of the victim
B7 Privacy true the eyes of the victim
VSE 2016
 
C4 Cross border support for cross border victims: a knowledge sharing experiment
C4 Cross border support for cross border victims: a knowledge sharing experimentC4 Cross border support for cross border victims: a knowledge sharing experiment
C4 Cross border support for cross border victims: a knowledge sharing experiment
VSE 2016
 
A3 What do victims want regarding restorative justice and how can we meet the...
A3 What do victims want regarding restorative justice and how can we meet the...A3 What do victims want regarding restorative justice and how can we meet the...
A3 What do victims want regarding restorative justice and how can we meet the...
VSE 2016
 
B8 Cross-cultural and comparative victimology
B8 Cross-cultural and comparative victimologyB8 Cross-cultural and comparative victimology
B8 Cross-cultural and comparative victimology
VSE 2016
 
B5 The recovery-phase in the aftermath of mass violence or terrorism
B5 The recovery-phase in the aftermath of mass violence or terrorismB5 The recovery-phase in the aftermath of mass violence or terrorism
B5 The recovery-phase in the aftermath of mass violence or terrorism
VSE 2016
 
A1 Youngsters victimization prevention: how to prevent online grooming and un...
A1 Youngsters victimization prevention: how to prevent online grooming and un...A1 Youngsters victimization prevention: how to prevent online grooming and un...
A1 Youngsters victimization prevention: how to prevent online grooming and un...
VSE 2016
 
B2 Ondersteuning van slachtoffers van terrorisme / grensoverschrijdend slacht...
B2 Ondersteuning van slachtoffers van terrorisme / grensoverschrijdend slacht...B2 Ondersteuning van slachtoffers van terrorisme / grensoverschrijdend slacht...
B2 Ondersteuning van slachtoffers van terrorisme / grensoverschrijdend slacht...
VSE 2016
 
B8 Cross-cultural and comparative victimology
B8 Cross-cultural and comparative victimologyB8 Cross-cultural and comparative victimology
B8 Cross-cultural and comparative victimology
VSE 2016
 
D4 Cross-border cases, especially murder abroad
D4 Cross-border cases, especially murder abroadD4 Cross-border cases, especially murder abroad
D4 Cross-border cases, especially murder abroad
VSE 2016
 

Viewers also liked (10)

C7 Victim rights’ and the right to a fair trial
C7 Victim rights’ and the right to a fair trialC7 Victim rights’ and the right to a fair trial
C7 Victim rights’ and the right to a fair trial
 
B7 Privacy true the eyes of the victim
B7 Privacy true the eyes of the victimB7 Privacy true the eyes of the victim
B7 Privacy true the eyes of the victim
 
C4 Cross border support for cross border victims: a knowledge sharing experiment
C4 Cross border support for cross border victims: a knowledge sharing experimentC4 Cross border support for cross border victims: a knowledge sharing experiment
C4 Cross border support for cross border victims: a knowledge sharing experiment
 
A3 What do victims want regarding restorative justice and how can we meet the...
A3 What do victims want regarding restorative justice and how can we meet the...A3 What do victims want regarding restorative justice and how can we meet the...
A3 What do victims want regarding restorative justice and how can we meet the...
 
B8 Cross-cultural and comparative victimology
B8 Cross-cultural and comparative victimologyB8 Cross-cultural and comparative victimology
B8 Cross-cultural and comparative victimology
 
B5 The recovery-phase in the aftermath of mass violence or terrorism
B5 The recovery-phase in the aftermath of mass violence or terrorismB5 The recovery-phase in the aftermath of mass violence or terrorism
B5 The recovery-phase in the aftermath of mass violence or terrorism
 
A1 Youngsters victimization prevention: how to prevent online grooming and un...
A1 Youngsters victimization prevention: how to prevent online grooming and un...A1 Youngsters victimization prevention: how to prevent online grooming and un...
A1 Youngsters victimization prevention: how to prevent online grooming and un...
 
B2 Ondersteuning van slachtoffers van terrorisme / grensoverschrijdend slacht...
B2 Ondersteuning van slachtoffers van terrorisme / grensoverschrijdend slacht...B2 Ondersteuning van slachtoffers van terrorisme / grensoverschrijdend slacht...
B2 Ondersteuning van slachtoffers van terrorisme / grensoverschrijdend slacht...
 
B8 Cross-cultural and comparative victimology
B8 Cross-cultural and comparative victimologyB8 Cross-cultural and comparative victimology
B8 Cross-cultural and comparative victimology
 
D4 Cross-border cases, especially murder abroad
D4 Cross-border cases, especially murder abroadD4 Cross-border cases, especially murder abroad
D4 Cross-border cases, especially murder abroad
 

Similar to Kotlin talk

Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in Kotlin
Dmitriy Sobko
 
PostgreSQL and PL/Java
PostgreSQL and PL/JavaPostgreSQL and PL/Java
PostgreSQL and PL/Java
Peter Eisentraut
 
Group111
Group111Group111
Practical tips for building apps with kotlin
Practical tips for building apps with kotlinPractical tips for building apps with kotlin
Practical tips for building apps with kotlin
Adit Lal
 
Save time with kotlin in android development
Save time with kotlin in android developmentSave time with kotlin in android development
Save time with kotlin in android development
Adit Lal
 
Create your DSL with Kotlin
Create your DSL with KotlinCreate your DSL with Kotlin
Create your DSL with Kotlin
LINE Corporation
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
JAX London
 
Paging Like A Pro
Paging Like A ProPaging Like A Pro
Paging Like A Pro
Gabor Varadi
 
Google App Engine With Java And Groovy
Google App Engine With Java And GroovyGoogle App Engine With Java And Groovy
Google App Engine With Java And Groovy
Ken Kousen
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
Howard Lewis Ship
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
Mahmoud Samir Fayed
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
Eberhard Wolff
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
lennartkats
 
Liferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for DevelopersLiferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for Developers
Azilen Technologies Pvt. Ltd.
 
2012: ql.io and Node.js
2012: ql.io and Node.js2012: ql.io and Node.js
2012: ql.io and Node.js
Jonathan LeBlanc
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
Andres Almiray
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
Schalk Cronjé
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
Matthew Clarke
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
MobileAcademy
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
Tarek Yehia
 

Similar to Kotlin talk (20)

Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in Kotlin
 
PostgreSQL and PL/Java
PostgreSQL and PL/JavaPostgreSQL and PL/Java
PostgreSQL and PL/Java
 
Group111
Group111Group111
Group111
 
Practical tips for building apps with kotlin
Practical tips for building apps with kotlinPractical tips for building apps with kotlin
Practical tips for building apps with kotlin
 
Save time with kotlin in android development
Save time with kotlin in android developmentSave time with kotlin in android development
Save time with kotlin in android development
 
Create your DSL with Kotlin
Create your DSL with KotlinCreate your DSL with Kotlin
Create your DSL with Kotlin
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Paging Like A Pro
Paging Like A ProPaging Like A Pro
Paging Like A Pro
 
Google App Engine With Java And Groovy
Google App Engine With Java And GroovyGoogle App Engine With Java And Groovy
Google App Engine With Java And Groovy
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 
Liferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for DevelopersLiferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for Developers
 
2012: ql.io and Node.js
2012: ql.io and Node.js2012: ql.io and Node.js
2012: ql.io and Node.js
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 

Kotlin talk

  • 4. • Designed and developed by JetBrains • Statically-typed programming language • Compiles to JVM bytecode, runs on JVM • v1.0 released on February 16, 2016 • Latest version 1.0.2 (Android Lint Checks, method count reduced ~1500)
  • 6. • Null safety • Functions • Sequences • Extensions • Data classes
  • 8. • String templates • ‘when' expression • Smart casts • Kotlin from Java - @JvmOverloads
  • 10. • Install Kotlin IDEA plugin • Enable Kotlin Android plugin • Enable Kotlin Android Extensions plugin • Add stdlib dependency
  • 11. Setup with AS Install IDEA Kotlin plugin
  • 12. Add Kotlin plugin to build.gradle buildscript {
 ext.kotlin_version = ‘<kotlin_version>'
 repositories {
 mavenCentral()
 }
 dependencies {
 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
 }
 }
 apply plugin: 'com.android.application'
 apply plugin: 'kotlin-android' android {
 ...
 sourceSets {
 main.java.srcDirs += 'src/main/kotlin'
 }
 } dependencies {
 ...
 compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
 }
  • 13. Kotlin Android Extensions • Part of Kotlin IDEA plugin • View binder library similar to Butterknife • Plugin for the Kotlin compiler • Based on extensions properties
  • 14. Add Kotlin Android Extensions plugin to build.gradle apply plugin: 'kotlin-android-extensions' Usage <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/container"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"/> Without extensions findViewById(R.id.container)?.visibility = View.INVISIBLE With extensions import kotlinx.android.synthetic.main.activity_delightful.* container.visibility = View.INVISIBLE

  • 16. • Aims to eliminate NPE danger in code • NPE can be thrown explicitly or by usage of !! operator (for NPE lovers :)) • By default references cannot be null • Allow null with ? operator
  • 17. Do not allow null values data class Clip(val title: String) data class FeedPost(var clip: Clip) var data = FeedPost(Clip(null)) //Won't compile Allow null values data class Clip(val title: String?) data class FeedPost(var clip: Clip?) var data = FeedPost(Clip(null)) //Will compile Results to var data:FeedPost? = fetchFromBackend() //Some code that maybe sets data reference
 textView.text = (data?.clip?.title) Java if(data != null && data.clip != null && data.clip.title != null) {
 //Code that uses data
 } What about this? fun setText(title:String) {
 } setText(data?.clip?.title!!)
  • 19. • Top level functions support • Default Arguments • Named Arguments • Higher-Order Functions and Lambdas • Inline functions • Extension Functions
  • 20. Default arguments Java private void setData(List<Clip> clipList, Set<String> ids, boolean reset) {
 ...
 } Kotlin private fun setData(clipList: List<Clip>, ids: Set<String> = emptySet<String>(), reset: Boolean = false) { ... } setData(loadedDataFromBackend, emptySet(), true) 
 setData(loadedDataFromBackend)
  • 21. Named arguments Let’s add a few more parameters to setData function Java private void setData(List<Clip> clipList, Set<String> ids, boolean reset, boolean orderDescending, boolean skipViewed) {
 } setData(loadedDataFromBackend, new HashSet<String>(), false, true, false); Kotlin private fun setData(clipList: List<Clip>, ids: Set<String> = emptySet(), reset: Boolean = false,
 orderDescending: Boolean = false, skipViewed: Boolean = false) {
 } setData(clipList = emptyList(), reset = true, skipViewed = false, orderDescending = true)
  • 23. • A higher-order function takes functions as parameter, or returns a function • A lambda expression or an anonymous function is a function that is not declared, but passed immediately as an expression
  • 24. Lambda syntax for MenuItemClickListener var menuItemClickListenerLambdaFunction: (MenuItem) -> Boolean = { menuItem -> true } Concise version var menuItemClickListenerLambdaFunction = { menuItem: MenuItem ->
 if (menuItem.itemId == R.id.menu_settings) {
 true
 }
 false
 } MenuItemClickListener in Java OnMenuItemClickListener onMenuItemClickListener = new Toolbar.OnMenuItemClickListener() {
 @Override
 public boolean onMenuItemClick(MenuItem item) {
 return false;
 }
 };
  • 25. Compared to lambdas in Java • Retrolambda (replaces lambdas with anonymous class through bytecode manipulation) • Compile with Android N (lambda is compiled into class with constructor and method) • Increasing method count and creating pressure on GC • Kotlin generates bytecode from lambdas using inline functions
  • 27. • Inside kotlin.sequences • Similar to Java 8 Streams API • Implemented as extension functions • zip, map, reduce, filter etc…
  • 28. Suppose we have a collection of video clips, where each clip has an id. We would like to store ids of clips where the title length is less than 10 characters in a separate collection Java for(Clip item : items) {
 if(item.getTitle().length() < 10) {
 ids.add(item.getId());
 }
 } Kotlin items.map { it -> it.id }.filter { it -> it.length < 10 }.forEach { it -> ids.add(it) } items.map { it.id }.filter { it.length < 10 }.forEach { ids.add(it) }
  • 29. In Java? • Streams API in Java 8 with Android N • RxJava
  • 31. • Add functionality to a class without extending it • Support through extension functions and extension properties • Get rid of StringUtils, ViewUtils classes
  • 32. Extension properties val <Context> Context.context: android.content.Context?
 get() = getApplicationContext() val <Activity> Activity.view_pager: android.support.v4.view.ViewPager?
 get() = findViewById(R.id.view_pager) as android.support.v4.view.ViewPager?
  • 33. • Prefix function name with class name that we are extending • All class methods and fields are available inside the extension function • No actual classes are modified. Functions are callable with the dot- notation on instances of this class Extension Functions
  • 34. Example 1 Java public static float convertDpToPixel(Context context, float dp){
 Resources resources = context.getResources();
 DisplayMetrics metrics = resources.getDisplayMetrics();
 return dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
 } Kotlin fun Context.dpToPx(dp: Float): Int {
 val resources = this.resources
 val metrics = resources.displayMetrics
 return (dp * (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)).toInt()
 } //Inside Activity
 val dp = dpToPx(6f)
  • 35. Example 2 Java Context context = getApplicationContext();
 Drawable tintedDrawable = DrawableCompat.wrap(ContextCompat.getDrawable(context, R.drawable.ic_arrow));
 DrawableCompat.setTint(tintedDrawable, ContextCompat.getColor(context, R.color.colorAccentDark));
 DrawableCompat.unwrap(tintedDrawable); Kotlin fun Drawable.tint(context: Context,
 @ColorRes color: Int): Drawable {
 val tintedDrawable = DrawableCompat.wrap(this)
 DrawableCompat.setTint(tintedDrawable, ContextCompat.getColor(context, color))
 DrawableCompat.unwrap<Drawable>(this)
 return tintedDrawable
 } ContextCompat.getDrawable(applicationContext, R.drawable.ic_arrow).tint(applicationContext, R.color.colorAccentDark)
  • 36. More complex example fun ImageView.loadUrl(path: String?,
 transformation: RequestCreator.() -> RequestCreator = { this }) =
 Picasso.with(context).load(path).transformation().into(this) thumbnailView.loadUrl(thumbnailUrl) {
 transform(RoundedCornersTransformation(
 thumbnailView.context.dpToPx(4f), 0
 )).fit()
 }
  • 37. • loadUrl function takes functions as a second parameter • when calling loadUrl function we pass a function that will be invoked
  • 38.
  • 40. • Intented to hold data • Auto generated equals(), hashCode(), toString() and copy() • At least one parameter in constructor • Can’t be abstract • Can implement, can’t extend…for now
  • 41. Example data class Clip(val id: String, val title: String) @PaperParcel
 data class Clip(val id: String, val title: String) : PaperParcelable {
 companion object {
 @JvmField val CREATOR = PaperParcelable.Creator(Clip::class.java)
 }
 } with Parcelable
  • 43. String templates private fun setData(clipList: List<Clip>, ids: Set<String> = emptySet(), reset: Boolean = false,
 orderDescending: Boolean = false, skipViewed: Boolean = false) {
 Timber.i("Log parameters number of clip:${clipList.size} orderDescending:$orderDescending ")
 }
  • 44. When expression Create view holder Java @Override
 public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
 switch (viewType) {
 case VIEW_TYPE_ONE:
 return new ViewHolderOne(LayoutInflater
 .from(parent.getContext())
 .inflate(R.layout.item_layout_one, parent, false));
 
 case VIEW_TYPE_TWO:
 return new ViewHolderTwo(LayoutInflater
 .from(parent.getContext())
 .inflate(R.layout.item_layout_two, parent, false));
 
 case VIEW_TYPE_THREE:
 return new ViewHolderThree(LayoutInflater
 .from(parent.getContext())
 .inflate(R.layout.item_layout_three, parent, false));
 
 default:
 throw new RuntimeException();
 }
 }
  • 45. Kotlin override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) {
 VIEW_TYPE_ONE -> ViewHolderOne(parent.inflate<View>(R.layout.item_layout_one))
 VIEW_TYPE_TWO -> ViewHolderTwo(parent.inflate<View>(R.layout.item_layout_two))
 VIEW_TYPE_THREE -> ViewHolderThree(parent.inflate<View>(R.layout.item_layout_three))
 else -> throw RuntimeException("Invalid view type.")
 }

  • 46. Smart casts • Cast by using is or !is operator • Compiler tracks is-checks for immutable values and inserts casts automatically
  • 47. Java @Override
 public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
 if (holder instanceof ViewHolderOne) {
 ViewHolderOne holderOne = (ViewHolderOne) holder;
 } else if (holder instanceof ViewHolderTwo) {
 ViewHolderTwo holderTwo = (ViewHolderTwo) holder;
 } else if (holder instanceof ViewHolderThree) {
 ViewHolderThree holderThree = (ViewHolderThree) holder;
 }
 } Example with binding view holder
  • 48. Kotlin override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
 if (holder is ViewHolderOne) {
 val holderOne:ViewHolderOne = holder
 } else if (holder is ViewHolderTwo) {
 val holder:TwoViewHolderTwo = holder
 } else if (holder is ViewHolderThree) {
 val holder:ThreeViewHolderThree = holder
 }
 } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) = when(holder){
 is ClipAdapter.ViewHolderOne -> ...
 is ClipAdapter.ViewHolderTwo -> ...
 is ClipAdapter.ViewHolderThree -> ...
 } or even better
  • 49. @JvmOverloads • Call Kotlin from Java • Provide all versions of constructor
  • 50. Example by extending a view class ActivityView(context: Context, 
 attrs: AttributeSet? = null, 
 defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr){
 
 constructor(context: Context):this(context, null, -1) {
 }
 constructor(context: Context, attrs: AttributeSet? ):this(context, attrs, -1) {
 } } class ActivityView : RelativeLayout {
 @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
 : super(context, attrs, defStyleAttr) }
  • 51. Future is bright • Gradle scripting in Kotlin • Incremental compilation • Data class inheritance support • Java 8/9 support • Jack & Jill toolchain integration
  • 52. Any apps out there? • Expedia Hotels, Flights & Cars • BlueCrew • Level Money • LifeHack Chisinau • Changelogs
  • 53. I want more • http://antonioleiva.com/kotlin/ • https://kotlinlang.org/docs/ reference/ • http://kotlinlang.slack.com/
  • 55. Thanks Code Android with joy. Try Kotlin.