SlideShare a Scribd company logo
Why you should try to
write app in
You really should
Code less, mean
more
What changes?
; и new - bye bye!
function is object. - it can be linked and set as argument
val function:()->Unit = {}
fun function1(func:()->Unit){
func.invoke() // or function()
}
val referenceFun = function1(function)
No more void - fun SomeFunction() Unit object if we need to return nothing from
generics
fun SomeFunction():Result<Unit>
No primitives, only Int,Long,Double,Boolean - no value wrapping/unwrapping
operators +,-,/,* - are functions, and they can be overriden for classes
class SomeClass(){
public operator fun plus(other: SomeClass): SomeClass {
return SomeClass()
}
}
val sum = SomeClass()+SomeClass()
What changes?
class SomeClass(val id: String = "") {
val isBlank: Boolean get() = id.isEmpty()
}
if(SomeClass().isBlank){
//do something
}
Default class constructor
Default arguments
class Person(val firstName: String)
class Customer(val customerName: String = "")
Property with defaults and override
class User(
val id: String,
val name: String = "user name",
val email: String = "user@email.com"
)
val person = Person()
val customer = Customer()
val user1 = User("uniqueId")
val user2 = User("uniqueId1",
email = "user2@email.com")
What changes?
Singletone pattern
val x: String? = y as String?
if (obj is SomeObjectType) {
//do something
}
object SomeSingletoneClass()
Type casting and type checking
window.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
// ...
}
override fun mouseEntered(e: MouseEvent) {
// ...
}
})
What changes?
when (obj) {
1 -> print("One")
"Hello" -> print("Greeting")
is Long -> print("Long")
!is String -> print("Not a string")
else -> print("Unknown")
}
All expressions are functions and they can return result
fun max(a: Int, b: Int): Int {
return if (a > b)
a
else
b
}
Non nullable properties by default
- WTF? Java fault? What can we do?
- forget this s**t except you really need it
- compile errorval string : String = null
val string : String? = null - OK
item?.property?.property?.property?
item!!.property.property
val string : String = item?.property ?: "Default string"
Data classes
Auto implement equals() hashCode() toString()
copy() - with ability to change property declared in constructor
Ability to auto implement Parcelable by @Parcelable
constructor data class User(val name: String, val age: Int)
Cons: not a very good support from
ORM , realm, room
val person1 = Person("Chike", "Mgbemena")
println(person1) // Person(firstName=Chike, lastName=Mgbemena)
val person2 = person1.copy(lastName = "Onu")
println(person2) //Person3(firstName=Chike, lastName=Onu)
Companion objects
All statics methods are only for internal use
class SomeActivity : AppCompatActivity() {
companion object {
fun start(activity: Context) {
val intent = Intent(activity, SomeActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or
Intent.FLAG_ACTIVITY_NEW_TASK)
activity.startActivity(intent)
}
}
}
Companions a creates as separated object in memory and quickly clears.
Extension functions will replace them as good alternative
Kotlin call-DebugViewActivity.start(this)
Java call-DebugViewActivity.Companion.start(this)
Collections
by List<Any> immutable
use MutableList<Any>
list.flat{predicate*}
list.map{predicate*}
list.forEach{predicate*}
list.filter{predicate*}
list.first{predicate*}
list.lastOrNull{predicate*}
Big amount of collection methods not available for java
collection
.first { it.id == someId }
.innerPropertyList
.firstOrNull { it.id == innerItemId }
?.let {
doSomething(it)
}
All collection initialization by collection builders
listOf(), arrayOf(), mapOf(), mutableListOf(), emptyListOf() etc
Property delegates
Makes properties smarter
val someView: by lazy {findViewById(R.id.someView)}
var name: String by Delegates.observable("<no name>") {
prop, old, new ->
println("$old -> $new")
}
fun <T : View?> AppCompatActivity.bind(@IdRes idRes: Int): Lazy<T> {
@Suppress(«UNCHECKED_CAST")
return unsafeLazy { findViewById<T>(idRes) }
}
class Activity:AppCompatActivity(){
private val toolbar by bind<Toolbar>(R.id.mainToolbar)
********
}
Class delegates
Remove your multiple chain inheritance
interface ISomeLogic {
fun doSomeThing()
}
class SomeClass(object: ISomeLogic) : ISomeLogic by object
SomeClass().doSomeThing()
Extension functions & properties
fun Activity.intentString(name: String): String {
return this.intent.getStringExtra(name)
}
private val itemId by lazy { intentString(ITEM_ID) }
val EditText.isEmailPattern: Boolean
get() {
return Patterns.EMAIL_ADDRESS.matcher(text.toString()).matches()
}
if(emailEditView.isEmailPattern){
}
Extension functions & properties
fun Context.isOnline(): Boolean {
val cm = this.getSystemService(Context.CONNECTIVITY_SERVICE) as
ConnectivityManager
val netInfo = cm.activeNetworkInfo
return netInfo != null && netInfo.isConnectedOrConnecting
}
Coroutines
And we can start new speech here, cause its very big theme
Coroutines
suspend keyword - exist in language level and inform that this function can pause it
execution
Coroutines differs from Runables in java.concurency
Coroutines don’t block thread
Coroutines are critically lightweight
Kotlin, as a language, help to use coroutines
suspend fun doSomething(foo: Foo): Bar {
...
}
Coroutines
suspend keyword - exist in language level and inform that this function can pause it
execution
fun <T> BG(block: suspend () -> T): Deferred<T> { // non blocking operation on
BackgroundThread with returning result
return async<T>(CommonPool) {
block.invoke()
}
}
fun UI(block: suspend () -> Unit): Job { // non blocking operation on UI thread
return async(kotlinx.coroutines.experimental.android.UI) {
block.invoke()
}
}
private fun someAsynkFlow() = UI {
val someHeavyWorkResult = BG { doSomeHeavyWork() }
val someHeavyWork1Result = BG { doSomeHeavyWork1() }
useBothResultsForUpdateUi(someHeavyWorkResult.await(),someHeavyWork1Result.await())
}
Coroutines
Ability to call function with callback inside a «linear» coroutine call
private suspend fun doSomeHeavyWork(): Result =
suspendCancellableCoroutine<Result> {
doSomeWorkWithCallback(object : Callback() {
override fun onSuccess(result: Result) {
it.resume(result)
}
override fun onError(error: Exception) {
it.resumeWithException(error)
}
})
}
Conclusions +
Kotlin is not a panacea, but it really helps to develop your app
Kotlin make your code less to 10-20%
Kotlin brings to your code new abilities and can help you to remove heavy
dependencies like ButterKnife Dagger Guava etc.
80% Google Play apps uses Kotlin in some ways
Kotlin make code more readable
Kotlin brings functional programming elements to your code
Kotlin-extentions make life of android developer less tragic
Conclusions -
Kotlin is not a panacea and without good practices I have a bad news for you
Kotlin performance is less from java by 1-2% in execution and 5-15% in compile
https://medium.com/keepsafe-engineering/kotlin-vs-java-compilation-speed-
e6c174b39b5d
Kotlin-extentions - less performance
Waiting for better Android Studio support of kotlin
https://hackernoon.com/kotlin-is-still-not-top-citizen-of-android-studio-3-0-
af11560516c6
Not all old libraries have good kotlin support. Sometimes developers doesn’t want
to update them
Future
Kotlin native - for ndk replacement, maybe :)
data class support for libraries
Kotlin DSL - for gradle script replacement (currently in early alpha now)
Performance improving
Contacts
Slack: kremendev@slack.com Serhii Chaban
Twitter:@SerhiiChaban
Email: serhii.chaban@gmail.com
Facebook:serhiichaban

More Related Content

What's hot

Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
Paweł Byszewski
 
Kotlin
KotlinKotlin
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
 
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
Muhammad Raza
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Neuroevolution in Elixir
Neuroevolution in ElixirNeuroevolution in Elixir
Neuroevolution in Elixir
Jeff Smith
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
NAVER Engineering
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
Jose Manuel Ortega Candel
 
Hammurabi
HammurabiHammurabi
Hammurabi
Mario Fusco
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan s.r.o.
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
Kirill Rozov
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
Jaanus Pöial
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
Guido Pio Mariotti
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy Development
Md Sazzad Islam
 
Swift 2
Swift 2Swift 2
Swift 2
Jens Ravens
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Tudor Dragan
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
Myeongin Woo
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
John De Goes
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
DEVTYPE
 

What's hot (20)

Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
Kotlin
KotlinKotlin
Kotlin
 
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)
 
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
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Neuroevolution in Elixir
Neuroevolution in ElixirNeuroevolution in Elixir
Neuroevolution in Elixir
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy Development
 
Swift 2
Swift 2Swift 2
Swift 2
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 

Similar to Kotlin for android developers whats new

Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - Coroutine
Sean Tsai
 
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
DroidConTLV
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
Artur Latoszewski
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
Hermann Hueck
 
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)
Gesh Markov
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Codemotion
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
IoT Best practices
 IoT Best practices IoT Best practices
IoT Best practices
CocoaHeads France
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
SQLI
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
Samir Chekkal
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
Minseo Chayabanjonglerd
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicGraham Dumpleton
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicNew Relic
 
Using zone.js
Using zone.jsUsing zone.js
Using zone.js
Standa Opichal
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
Hermann Hueck
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
Sergey Bandysik
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
Knoldus Inc.
 
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super PowersJDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
PROIDEA
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 

Similar to Kotlin for android developers whats new (20)

Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - Coroutine
 
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
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
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)
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
IoT Best practices
 IoT Best practices IoT Best practices
IoT Best practices
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
Using zone.js
Using zone.jsUsing zone.js
Using zone.js
 
Future vs. Monix Task
Future vs. Monix TaskFuture vs. Monix Task
Future vs. Monix Task
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super PowersJDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 

Recently uploaded

Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
abh.arya
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 

Recently uploaded (20)

Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 

Kotlin for android developers whats new

  • 1. Why you should try to write app in You really should
  • 3. What changes? ; и new - bye bye! function is object. - it can be linked and set as argument val function:()->Unit = {} fun function1(func:()->Unit){ func.invoke() // or function() } val referenceFun = function1(function) No more void - fun SomeFunction() Unit object if we need to return nothing from generics fun SomeFunction():Result<Unit> No primitives, only Int,Long,Double,Boolean - no value wrapping/unwrapping operators +,-,/,* - are functions, and they can be overriden for classes class SomeClass(){ public operator fun plus(other: SomeClass): SomeClass { return SomeClass() } } val sum = SomeClass()+SomeClass()
  • 4. What changes? class SomeClass(val id: String = "") { val isBlank: Boolean get() = id.isEmpty() } if(SomeClass().isBlank){ //do something } Default class constructor Default arguments class Person(val firstName: String) class Customer(val customerName: String = "") Property with defaults and override class User( val id: String, val name: String = "user name", val email: String = "user@email.com" ) val person = Person() val customer = Customer() val user1 = User("uniqueId") val user2 = User("uniqueId1", email = "user2@email.com")
  • 5. What changes? Singletone pattern val x: String? = y as String? if (obj is SomeObjectType) { //do something } object SomeSingletoneClass() Type casting and type checking window.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { // ... } override fun mouseEntered(e: MouseEvent) { // ... } })
  • 6. What changes? when (obj) { 1 -> print("One") "Hello" -> print("Greeting") is Long -> print("Long") !is String -> print("Not a string") else -> print("Unknown") } All expressions are functions and they can return result fun max(a: Int, b: Int): Int { return if (a > b) a else b } Non nullable properties by default - WTF? Java fault? What can we do? - forget this s**t except you really need it - compile errorval string : String = null val string : String? = null - OK item?.property?.property?.property? item!!.property.property val string : String = item?.property ?: "Default string"
  • 7. Data classes Auto implement equals() hashCode() toString() copy() - with ability to change property declared in constructor Ability to auto implement Parcelable by @Parcelable constructor data class User(val name: String, val age: Int) Cons: not a very good support from ORM , realm, room val person1 = Person("Chike", "Mgbemena") println(person1) // Person(firstName=Chike, lastName=Mgbemena) val person2 = person1.copy(lastName = "Onu") println(person2) //Person3(firstName=Chike, lastName=Onu)
  • 8. Companion objects All statics methods are only for internal use class SomeActivity : AppCompatActivity() { companion object { fun start(activity: Context) { val intent = Intent(activity, SomeActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK) activity.startActivity(intent) } } } Companions a creates as separated object in memory and quickly clears. Extension functions will replace them as good alternative Kotlin call-DebugViewActivity.start(this) Java call-DebugViewActivity.Companion.start(this)
  • 9. Collections by List<Any> immutable use MutableList<Any> list.flat{predicate*} list.map{predicate*} list.forEach{predicate*} list.filter{predicate*} list.first{predicate*} list.lastOrNull{predicate*} Big amount of collection methods not available for java collection .first { it.id == someId } .innerPropertyList .firstOrNull { it.id == innerItemId } ?.let { doSomething(it) } All collection initialization by collection builders listOf(), arrayOf(), mapOf(), mutableListOf(), emptyListOf() etc
  • 10. Property delegates Makes properties smarter val someView: by lazy {findViewById(R.id.someView)} var name: String by Delegates.observable("<no name>") { prop, old, new -> println("$old -> $new") } fun <T : View?> AppCompatActivity.bind(@IdRes idRes: Int): Lazy<T> { @Suppress(«UNCHECKED_CAST") return unsafeLazy { findViewById<T>(idRes) } } class Activity:AppCompatActivity(){ private val toolbar by bind<Toolbar>(R.id.mainToolbar) ******** }
  • 11. Class delegates Remove your multiple chain inheritance interface ISomeLogic { fun doSomeThing() } class SomeClass(object: ISomeLogic) : ISomeLogic by object SomeClass().doSomeThing()
  • 12. Extension functions & properties fun Activity.intentString(name: String): String { return this.intent.getStringExtra(name) } private val itemId by lazy { intentString(ITEM_ID) } val EditText.isEmailPattern: Boolean get() { return Patterns.EMAIL_ADDRESS.matcher(text.toString()).matches() } if(emailEditView.isEmailPattern){ }
  • 13. Extension functions & properties fun Context.isOnline(): Boolean { val cm = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val netInfo = cm.activeNetworkInfo return netInfo != null && netInfo.isConnectedOrConnecting }
  • 14. Coroutines And we can start new speech here, cause its very big theme
  • 15. Coroutines suspend keyword - exist in language level and inform that this function can pause it execution Coroutines differs from Runables in java.concurency Coroutines don’t block thread Coroutines are critically lightweight Kotlin, as a language, help to use coroutines suspend fun doSomething(foo: Foo): Bar { ... }
  • 16. Coroutines suspend keyword - exist in language level and inform that this function can pause it execution fun <T> BG(block: suspend () -> T): Deferred<T> { // non blocking operation on BackgroundThread with returning result return async<T>(CommonPool) { block.invoke() } } fun UI(block: suspend () -> Unit): Job { // non blocking operation on UI thread return async(kotlinx.coroutines.experimental.android.UI) { block.invoke() } } private fun someAsynkFlow() = UI { val someHeavyWorkResult = BG { doSomeHeavyWork() } val someHeavyWork1Result = BG { doSomeHeavyWork1() } useBothResultsForUpdateUi(someHeavyWorkResult.await(),someHeavyWork1Result.await()) }
  • 17. Coroutines Ability to call function with callback inside a «linear» coroutine call private suspend fun doSomeHeavyWork(): Result = suspendCancellableCoroutine<Result> { doSomeWorkWithCallback(object : Callback() { override fun onSuccess(result: Result) { it.resume(result) } override fun onError(error: Exception) { it.resumeWithException(error) } }) }
  • 18. Conclusions + Kotlin is not a panacea, but it really helps to develop your app Kotlin make your code less to 10-20% Kotlin brings to your code new abilities and can help you to remove heavy dependencies like ButterKnife Dagger Guava etc. 80% Google Play apps uses Kotlin in some ways Kotlin make code more readable Kotlin brings functional programming elements to your code Kotlin-extentions make life of android developer less tragic
  • 19. Conclusions - Kotlin is not a panacea and without good practices I have a bad news for you Kotlin performance is less from java by 1-2% in execution and 5-15% in compile https://medium.com/keepsafe-engineering/kotlin-vs-java-compilation-speed- e6c174b39b5d Kotlin-extentions - less performance Waiting for better Android Studio support of kotlin https://hackernoon.com/kotlin-is-still-not-top-citizen-of-android-studio-3-0- af11560516c6 Not all old libraries have good kotlin support. Sometimes developers doesn’t want to update them
  • 20. Future Kotlin native - for ndk replacement, maybe :) data class support for libraries Kotlin DSL - for gradle script replacement (currently in early alpha now) Performance improving
  • 21. Contacts Slack: kremendev@slack.com Serhii Chaban Twitter:@SerhiiChaban Email: serhii.chaban@gmail.com Facebook:serhiichaban