SlideShare uma empresa Scribd logo
1 de 41
Baixar para ler offline
{ Kotlin }
Statically typed language for the JVM,
Android and the browser.
Developed by JetBrains
First stable release February 15, 2016.
{ Syntax }.var and val
var <propertyName>: <Type> = [property initializer]
get() // optional
set() // optional
//example
var str: String = “kotlin is awesome"
OR
var str = “kotlin is awesome"
{ Syntax }.method declaration
fun <methodName> : <ReturnType>
//example
fun saySomthing() : String {
return “kotlin is awesome"
}
OR
fun saySomthing() = “kotlin is awesome"
{ Syntax }
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
{ Syntax }
for ((k, v) in map) {
println("$k -> $v")
}
someObject?.let {
// execute this block if not null
}
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
{ Syntax }.inheritance
all classes by default are finals
open class Base {
open fun v() {}
fun nv() {}
}
class Derived() : Base() {
override fun v() {}
}
{ Syntax }.inheritance
open class A {
open fun f() { print("A") }
fun a() { print("a") }
}
interface B {
fun f() { print("B") }
fun b() { print("b") }
}
class C() : A(), B {
// The compiler requires f() to be overridden:
override fun f() {
super<A>.f() // call to A.f()
super<B>.f() // call to B.f()
}
}
{ Syntax }.inner classes
class A { // implicit label @A
inner class B { // implicit label @B
fun foo() {
val a = this@A // A's this
val b = this@B // B's this
}
}
}
Billion-dollar
mistake
Tony Hoare
My goal was to ensure that all use of references should
be absolutely safe, with checking performed automatically
by the compiler. But I couldn't resist the temptation to put
in a null reference, simply because it was so easy to
implement.
{ null safety } nullable and non-nullable types
var str: String = “kotlin is awesome"
str = null // compilation error… str is non-nullable type
var str: String? = “kotlin is awesome"
str = null // ok... str now can be null
val length = name.length // compilation error
val length = name?.length // ok
{ null safety } nullable and non-nullable types
var name: String? = “some string"
if (name != null){
length = name.length
}else{
length = 0
}
or more shortly
val length = name?.length ?: 0
{ Default parameters }
fun tmpMethod(a: Int = -10, b: Int = 5, c: Int = 0){
print(a + b + c)
}
----------------------------------------------------------------
tmpMethod(1) // 7
tmpMethod(2) // -8
tmpMethod(1,2,3) // 6
tmpMethod(b = 0, a = 2) // 2
{ Delegated Properties }
Lazy & Observable
{ Delegated Properties }
val lazyValue: String by lazy {
println("computed!")
"Hello"
}
fun main(args: Array<String>) {
println(lazyValue)
println(lazyValue)
}
This example prints:
computed!
Hello
Hello
{ Delegated Properties }
var age: Int by Delegates.observable(0) {
prop, old, new ->
println("$old -> $new")
}
age = 10 // 0 -> 10
age = 11 // 10 -> 11
{ No more Utils }.utilHell
{ Extensions }
Extension methods & Extension properties
{ Extensions }.methods
val nullableString : String? = null
if (nullableString.isNullOrEmpty()){
// nullableString is null or empty
}
{ Extensions }.methods
var myObject : MyClass? = null
if (myObject.isNull()){
// my object is null
}
{ Extensions }.methods
var myObject : MyClass? = null
if (myObject.isNull()){
// my object is null
}
fun MyClass?.isNull() : Boolean {
return this == null
}
OR
fun MyClass?.isNull() = this == null
{ Extensions }.methods
fun Activity.toast(msg: String, toastLength: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, msg, toastLength).show()
}
fun Fragment.toast(msg: String, toastLength: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, msg, toastLength).show()
}
{ Extensions }.properties
val myList = listOf(1,2,3,4,5)
val lastIndex = myList.lastIndex // lastIndex = 4
--------------------------------
{ Extensions }.properties
val myList = listOf(1,2,3,4,5)
val lastIndex = myList.lastIndex // lastIndex = 4
--------------------------------
val <T> List<T>.lastIndex: Int
get() = size - 1
{ Lambdas }
Collections.sort(items, { t1, t2 -> t1.name.compareTo(t2.name)})
---------------------------------------------------------------------------------------------------------
in java
Collections.sort(items, new Comparator<MyClass>() {
@Override
public int compare(MyClass t1, MyClass t2) {
return t1.getName().compareTo(t2.getName());
}
});
{ Higher-Order funcitons}
fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
val result = arrayListOf<R>()
for (item in this)
result.add(transform(item))
return result
}
val doubled = items.map { it * 2 }
fun <T> max(collection: Collection<T>,
less: (T, T) -> Boolean): T? {
var max: T? = null
for (it in collection)
if (max == null || less(max, it))
max = it
return max
}
val less = {a:Int,b:Int -> a > b}
Example of SqliteDatabase transaction in android
------------------------------------------------------------------------------------
db.beginTransaction()
try {
db.delete("tableName","firstName =?", arrayOf("Jake"))
db.setTransactionSuccessful()
}finally {
db.endTransaction()
}
Example of SqliteDatabase transaction in android
------------------------------------------------------------------------------------
db.beginTransaction()
try {
// do work here
db.setTransactionSuccessful()
}finally {
db.endTransaction()
}
{ Extension Function Expression }
db.inTransaction {
delete("tableName","firstName =?", arrayOf("Jake"))
}
{ Extension Function Expression }
fun SQLiteDatabase.inTransaction(func: () -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
}finally {
endTransaction()
}
}
db.inTransaction {
db.delete("tableName","firstName =?", arrayOf("Jake"))
}
{ Extension Function Expression }
fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
}finally {
endTransaction()
}
}
db.inTransaction {
delete("tableName","firstName =?", arrayOf("Jake"))
}
{ Kotlin in Android }
// in java
Button button = (Button) findViewById(R.id.my_button_id);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
}
});
// in kotlin
val button = findViewById(R.id.my_button_id) as Button
button.setOnClickListener { toast("clicked") }
{ Kotlin in Android }
// JAVA
button.getViewTreeObserver().addOnGlobalLayoutListener(new
ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
button.getViewTreeObserver().removeOnGlobalLayoutListener(this);
Toast.makeText(Main2Activity.this, button.getHeight() +"",
Toast.LENGTH_SHORT).show();
}
});
kotlin
any_type_view.afterMeasured {
toast(any_type_view.height.toString())
}
{ Extension Function Expression }
inline fun View.afterMeasured(crossinline f: View.() -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
f()
}
}
})
}
{ Kotlin in Android }
// in java
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "clicked",
Toast.LENGTH_SHORT).show();
}
});
// in kotlin
button.setOnClickListener {
toast("clicked")
}
{ Kotlin in Android }.no more findViewById
Syntetic import
apply plugin: 'kotlin-android-extensions'
my_button_id.setOnClickListener { }
my_text_view_id.text = "some text"
<Button
android:id="@+id/my_button_id"
android:layout_width="match_parent"
android:layout_height="50dp"
/>
<TextView
android:id="@+id/my_text_view_id"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
{ Kotlin in Android }.Anko library
{ Kotlin in Android }.Anko library
async() {
// Do something in a secondary thread
uiThread {
// Back to the main thread
}
}
{ Performance }
???
{ As fast as Java }
thanks ;)
https://kotlinlang.org/docs/reference/
http://antonioleiva.com/kotlin/
https://medium.com/keepsafe-engineering/kotlin-vs-java-compilation-speed-e6c174b39b5d#.8w0o4sh91
with kotlin you get
● lambdas
● default methods
● method references
● extension lambdas
● nullable types
● null safety
● inlined methods (which reduce the cost of lambdas immensely)
● extension methods
● improved type inference
● operator overloading (limited)
● infix methods
● reified generics for methods
● data classes
● property delegation
● interface delegation

Mais conteúdo relacionado

Mais procurados

Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
Chang W. Doh
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
intelliyole
 

Mais procurados (20)

Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functions
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Fractal proj report 2
Fractal proj report 2Fractal proj report 2
Fractal proj report 2
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
The Macronomicon
The MacronomiconThe Macronomicon
The Macronomicon
 
Swift 2
Swift 2Swift 2
Swift 2
 
Hello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC UnidebHello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC Unideb
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 

Destaque

Get Ready for Agile Methods: How to manage constant and rapid change in IT pr...
Get Ready for Agile Methods: How to manage constant and rapid change in IT pr...Get Ready for Agile Methods: How to manage constant and rapid change in IT pr...
Get Ready for Agile Methods: How to manage constant and rapid change in IT pr...
Dimitris Dranidis
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
Andrzej Sitek
 
An Empirical Study of Goto in C Code from GitHub Repositories
An Empirical Study of Goto in C Code from GitHub RepositoriesAn Empirical Study of Goto in C Code from GitHub Repositories
An Empirical Study of Goto in C Code from GitHub Repositories
SAIL_QU
 
Software reliability engineering
Software reliability engineeringSoftware reliability engineering
Software reliability engineering
Mark Turner CRP
 
certificates internship and training
certificates internship and trainingcertificates internship and training
certificates internship and training
Azhar Fanany
 
aravind report
aravind reportaravind report
aravind report
aravind r
 

Destaque (20)

Eclipse Day India 2015 - Keynote - Stephan Herrmann
Eclipse Day India 2015 - Keynote - Stephan HerrmannEclipse Day India 2015 - Keynote - Stephan Herrmann
Eclipse Day India 2015 - Keynote - Stephan Herrmann
 
Get Ready for Agile Methods: How to manage constant and rapid change in IT pr...
Get Ready for Agile Methods: How to manage constant and rapid change in IT pr...Get Ready for Agile Methods: How to manage constant and rapid change in IT pr...
Get Ready for Agile Methods: How to manage constant and rapid change in IT pr...
 
Get Functional on the CLR: Intro to Functional Programming with F#
Get Functional on the CLR: Intro to Functional Programming with F# Get Functional on the CLR: Intro to Functional Programming with F#
Get Functional on the CLR: Intro to Functional Programming with F#
 
No silver bullet
No silver bulletNo silver bullet
No silver bullet
 
No silver bullet essence and accidents of software engineering
No silver bullet essence and accidents of software engineeringNo silver bullet essence and accidents of software engineering
No silver bullet essence and accidents of software engineering
 
C# Async on iOS and Android - Miguel de Icaza, CTO of Xamarin
C# Async on iOS and Android - Miguel de Icaza, CTO of XamarinC# Async on iOS and Android - Miguel de Icaza, CTO of Xamarin
C# Async on iOS and Android - Miguel de Icaza, CTO of Xamarin
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Karumi Dojo: Kata Maxibon
Karumi Dojo: Kata MaxibonKarumi Dojo: Kata Maxibon
Karumi Dojo: Kata Maxibon
 
An Empirical Study of Goto in C Code from GitHub Repositories
An Empirical Study of Goto in C Code from GitHub RepositoriesAn Empirical Study of Goto in C Code from GitHub Repositories
An Empirical Study of Goto in C Code from GitHub Repositories
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
Software reliability engineering
Software reliability engineeringSoftware reliability engineering
Software reliability engineering
 
Chapter 7 software reliability
Chapter 7 software reliabilityChapter 7 software reliability
Chapter 7 software reliability
 
Agile Is the New Waterfall
Agile Is the New WaterfallAgile Is the New Waterfall
Agile Is the New Waterfall
 
Louisiana indian tribes
Louisiana indian tribesLouisiana indian tribes
Louisiana indian tribes
 
INCALZIREA GLOBALA
INCALZIREA GLOBALAINCALZIREA GLOBALA
INCALZIREA GLOBALA
 
Case Study - Rebranding Spa
Case Study - Rebranding SpaCase Study - Rebranding Spa
Case Study - Rebranding Spa
 
certificates internship and training
certificates internship and trainingcertificates internship and training
certificates internship and training
 
aravind report
aravind reportaravind report
aravind report
 
Covering the coup (whole article)
Covering the coup (whole article)Covering the coup (whole article)
Covering the coup (whole article)
 
Le influenze della globalizzazione sulle scelte di politica criminale. L’evol...
Le influenze della globalizzazione sulle scelte di politica criminale. L’evol...Le influenze della globalizzazione sulle scelte di politica criminale. L’evol...
Le influenze della globalizzazione sulle scelte di politica criminale. L’evol...
 

Semelhante a Kotlin

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 

Semelhante a Kotlin (20)

Introduction kot iin
Introduction kot iinIntroduction kot iin
Introduction kot iin
 
Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03
 
Let's fly to the Kotlin Island. Just an introduction to Kotlin
Let's fly to the Kotlin Island. Just an introduction to KotlinLet's fly to the Kotlin Island. Just an introduction to Kotlin
Let's fly to the Kotlin Island. Just an introduction to Kotlin
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Why Kotlin is your next language?
Why Kotlin is your next language? Why Kotlin is your next language?
Why Kotlin is your next language?
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)
 
Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

Kotlin

  • 1. { Kotlin } Statically typed language for the JVM, Android and the browser. Developed by JetBrains First stable release February 15, 2016.
  • 2. { Syntax }.var and val var <propertyName>: <Type> = [property initializer] get() // optional set() // optional //example var str: String = “kotlin is awesome" OR var str = “kotlin is awesome"
  • 3. { Syntax }.method declaration fun <methodName> : <ReturnType> //example fun saySomthing() : String { return “kotlin is awesome" } OR fun saySomthing() = “kotlin is awesome"
  • 4. { Syntax } when (x) { in 1..10 -> print("x is in the range") in validNumbers -> print("x is valid") !in 10..20 -> print("x is outside the range") else -> print("none of the above") }
  • 5. { Syntax } for ((k, v) in map) { println("$k -> $v") } someObject?.let { // execute this block if not null } fun foo(param: Int) { val result = if (param == 1) { "one" } else if (param == 2) { "two" } else { "three" } }
  • 6. { Syntax }.inheritance all classes by default are finals open class Base { open fun v() {} fun nv() {} } class Derived() : Base() { override fun v() {} }
  • 7. { Syntax }.inheritance open class A { open fun f() { print("A") } fun a() { print("a") } } interface B { fun f() { print("B") } fun b() { print("b") } } class C() : A(), B { // The compiler requires f() to be overridden: override fun f() { super<A>.f() // call to A.f() super<B>.f() // call to B.f() } }
  • 8. { Syntax }.inner classes class A { // implicit label @A inner class B { // implicit label @B fun foo() { val a = this@A // A's this val b = this@B // B's this } } }
  • 9. Billion-dollar mistake Tony Hoare My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement.
  • 10. { null safety } nullable and non-nullable types var str: String = “kotlin is awesome" str = null // compilation error… str is non-nullable type var str: String? = “kotlin is awesome" str = null // ok... str now can be null val length = name.length // compilation error val length = name?.length // ok
  • 11. { null safety } nullable and non-nullable types var name: String? = “some string" if (name != null){ length = name.length }else{ length = 0 } or more shortly val length = name?.length ?: 0
  • 12. { Default parameters } fun tmpMethod(a: Int = -10, b: Int = 5, c: Int = 0){ print(a + b + c) } ---------------------------------------------------------------- tmpMethod(1) // 7 tmpMethod(2) // -8 tmpMethod(1,2,3) // 6 tmpMethod(b = 0, a = 2) // 2
  • 13. { Delegated Properties } Lazy & Observable
  • 14. { Delegated Properties } val lazyValue: String by lazy { println("computed!") "Hello" } fun main(args: Array<String>) { println(lazyValue) println(lazyValue) } This example prints: computed! Hello Hello
  • 15. { Delegated Properties } var age: Int by Delegates.observable(0) { prop, old, new -> println("$old -> $new") } age = 10 // 0 -> 10 age = 11 // 10 -> 11
  • 16. { No more Utils }.utilHell
  • 17. { Extensions } Extension methods & Extension properties
  • 18. { Extensions }.methods val nullableString : String? = null if (nullableString.isNullOrEmpty()){ // nullableString is null or empty }
  • 19. { Extensions }.methods var myObject : MyClass? = null if (myObject.isNull()){ // my object is null }
  • 20. { Extensions }.methods var myObject : MyClass? = null if (myObject.isNull()){ // my object is null } fun MyClass?.isNull() : Boolean { return this == null } OR fun MyClass?.isNull() = this == null
  • 21. { Extensions }.methods fun Activity.toast(msg: String, toastLength: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, msg, toastLength).show() } fun Fragment.toast(msg: String, toastLength: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, msg, toastLength).show() }
  • 22. { Extensions }.properties val myList = listOf(1,2,3,4,5) val lastIndex = myList.lastIndex // lastIndex = 4 --------------------------------
  • 23. { Extensions }.properties val myList = listOf(1,2,3,4,5) val lastIndex = myList.lastIndex // lastIndex = 4 -------------------------------- val <T> List<T>.lastIndex: Int get() = size - 1
  • 24. { Lambdas } Collections.sort(items, { t1, t2 -> t1.name.compareTo(t2.name)}) --------------------------------------------------------------------------------------------------------- in java Collections.sort(items, new Comparator<MyClass>() { @Override public int compare(MyClass t1, MyClass t2) { return t1.getName().compareTo(t2.getName()); } });
  • 25. { Higher-Order funcitons} fun <T, R> List<T>.map(transform: (T) -> R): List<R> { val result = arrayListOf<R>() for (item in this) result.add(transform(item)) return result } val doubled = items.map { it * 2 } fun <T> max(collection: Collection<T>, less: (T, T) -> Boolean): T? { var max: T? = null for (it in collection) if (max == null || less(max, it)) max = it return max } val less = {a:Int,b:Int -> a > b}
  • 26. Example of SqliteDatabase transaction in android ------------------------------------------------------------------------------------ db.beginTransaction() try { db.delete("tableName","firstName =?", arrayOf("Jake")) db.setTransactionSuccessful() }finally { db.endTransaction() }
  • 27. Example of SqliteDatabase transaction in android ------------------------------------------------------------------------------------ db.beginTransaction() try { // do work here db.setTransactionSuccessful() }finally { db.endTransaction() }
  • 28. { Extension Function Expression } db.inTransaction { delete("tableName","firstName =?", arrayOf("Jake")) }
  • 29. { Extension Function Expression } fun SQLiteDatabase.inTransaction(func: () -> Unit) { beginTransaction() try { func() setTransactionSuccessful() }finally { endTransaction() } } db.inTransaction { db.delete("tableName","firstName =?", arrayOf("Jake")) }
  • 30. { Extension Function Expression } fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) { beginTransaction() try { func() setTransactionSuccessful() }finally { endTransaction() } } db.inTransaction { delete("tableName","firstName =?", arrayOf("Jake")) }
  • 31. { Kotlin in Android } // in java Button button = (Button) findViewById(R.id.my_button_id); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show(); } }); // in kotlin val button = findViewById(R.id.my_button_id) as Button button.setOnClickListener { toast("clicked") }
  • 32. { Kotlin in Android } // JAVA button.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { button.getViewTreeObserver().removeOnGlobalLayoutListener(this); Toast.makeText(Main2Activity.this, button.getHeight() +"", Toast.LENGTH_SHORT).show(); } }); kotlin any_type_view.afterMeasured { toast(any_type_view.height.toString()) }
  • 33. { Extension Function Expression } inline fun View.afterMeasured(crossinline f: View.() -> Unit) { viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (measuredWidth > 0 && measuredHeight > 0) { viewTreeObserver.removeOnGlobalLayoutListener(this) f() } } }) }
  • 34. { Kotlin in Android } // in java button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show(); } }); // in kotlin button.setOnClickListener { toast("clicked") }
  • 35. { Kotlin in Android }.no more findViewById Syntetic import apply plugin: 'kotlin-android-extensions' my_button_id.setOnClickListener { } my_text_view_id.text = "some text" <Button android:id="@+id/my_button_id" android:layout_width="match_parent" android:layout_height="50dp" /> <TextView android:id="@+id/my_text_view_id" android:layout_width="match_parent" android:layout_height="wrap_content" />
  • 36. { Kotlin in Android }.Anko library
  • 37. { Kotlin in Android }.Anko library async() { // Do something in a secondary thread uiThread { // Back to the main thread } }
  • 39. { As fast as Java } thanks ;)
  • 41. with kotlin you get ● lambdas ● default methods ● method references ● extension lambdas ● nullable types ● null safety ● inlined methods (which reduce the cost of lambdas immensely) ● extension methods ● improved type inference ● operator overloading (limited) ● infix methods ● reified generics for methods ● data classes ● property delegation ● interface delegation