SlideShare a Scribd company logo
1 of 33
Download to read offline
Better Apps with Kotlin!
Pavel Shackih, SBT
t.me/PavelShackih
Motivation
Android core app quality: the app does not crash, force
close, freeze, or otherwise function abnormally on any
targeted device.
Motivation
Android core app quality: the app does not crash, force
close, freeze, or otherwise function abnormally on any
targeted device.
JSR-305, Android Support Annotations
@Nonnull
@Override
public User save(@Nonnull User user) {
// ...
userDao.save(user);
// ...
return user;
}
JSR-305, Android Support Annotations
1. Hard to maintain.
2. Verbose, but could be simplified using @ParametersAreNonnullByDefault or
@ParametersAreNullableByDefault.
3. Just warning.
4. “Leak” NPE.
5. ~6500 in SBOL.
Optional<T>
@Override
public Optional<User> findById(long id) {
return Optional.ofNullable(userDao.findById(id));
}
public void printUser(long id) {
Optional<User> optional = findById(id);
optional.ifPresent(user -> System.out.println(user));
}
Optional<T>
1. Verbose.
2. GC overhead.
3. Problem with third-party libraries.
Here comes Kotlin
fun main(args: Array<String>) {
val hello = "Hello, Innopolis!"
println(hello)
}
Here comes Kotlin
● statically-typed, object-oriented, functional;
● target: JVM, Android, JS, Native (in progress);
● fully interoperable with Java;
● compact runtime lib, good tooling;
● runs as fast as an equivalent on Java;
● easy to learn for Java developers;
● official Android development language.
Not nullable types by default
var foo: String = "Foo" // var foo = "Foo"
foo = null // Compile error: Null can not be a value of a non-null type String
var bar: String? = "Bar"
bar = null // Ok
bar = foo // Ok
foo = bar // Error
Not nullable types by default
String
String?
String? = String or null
Deal with nullable types
val user: User? = null
println(user.address.street)
// Error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable
receiver of type kotlin.String?
Smartcast
val user: User? = null
if (user != null && user.address != null) {
println(user.address.street) // Now: user: User, address: Address
}
User?
User
Address?
Address
Safe call operator ?.
val user: User? = null
println(user?.address)
if (user != null) {
return user.getAddress();
} else {
return null;
}
user?.address
user.address
null
*Kotlin in Action
user != null
user == null
Safe call operator always returns
nullable type of <T>, so <T> result type
transform to type <T?>
println(user?.address?.street)
Chaining safe call operators:
Elvis operator ?:
val user: User? = null
println(user ?: ADMIN)
if (user != null) {
return user;
} else {
return ADMIN;
}
user
user
ADMIN
*Kotlin in Action
user != null
user == null
println(user?.address?.street ?: UNKNOWN_STREET)
Let function
val user: User? = null
user?.let { println(it) }
if (user != null) {
System.out.println(user);
}
user
println(user)
user != null
*Kotlin in Action
Not null assertions: !! operator
val user: User? = null
println(user!!.address)
System.out.println(user.getAddress());
user
user.address
NullPointerException
*Kotlin in Action
user != null
user == null
Platform types and Java interoperability
Java Kotlin
@Nullable + String String?
@NotNull + String String
String String!
String! = String or String?
val stringValue = Java.getString()
println(stringValue.length) // Ok
println(stringValue?.length) // Ok
Kotlin nullability: Examples
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val id = savedInstanceState.getString(ID) // compile error
}
}
class MyIntentService : IntentService("MyIntentService") {
override fun onHandleIntent(intent: Intent?) {
val param1 = intent.getStringExtra(EXTRA_PARAM1) // compile error
}
}
Intrinsics
● Apply Intrinsics.checkParameterIsNotNull() for every public function for each
non-null parameter.
● Disable using -Xno-param-assertions or Proguard.
JDK 1.8 Kotlin
@Override
public void forEachRemaining(DoubleConsumer
action) {
Objects.requireNonNull(action);
if (count == -2) {
action.accept(first);
count = -1;
}
}
@NotNull
public User save(@NotNull User user) {
Intrinsics.checkParameterIsNotNull(user, "user");
this.userDao.save(user);
return user;
}
Kotlin nullability
1. Hard to maintain built-in type system.
2. Verbose special syntax for nullable values.
3. Not error, just a warning, no guarantees compile time error.
4. “Leak” NPE kotlin intrinsics.
5. GC overhead no overhead at all.
6. Problem with third-party libraries kotlin compiler could read default java
annotations from external byte code.
Extension functions
Java Kotlin
public static boolean isEmpty(@Nullable String string) {
return string == null || string.isEmpty();
}
fun String?.isEmpty(): Boolean {
return this == null || this.length == 0
}
String text = ...;
if (isEmpty(text)) {
System.out.println("Empty text!");
}
val text = ...
if (text.isEmpty()) {
println("Empty text!")
}
Extension functions: Lambdas
fun String.printWithCondition(predicate: (s: String) -> Boolean) {
if (predicate(this)) {
println(this)
}
}
val text = "Hello"
text.printWithCondition { it == "Hello" }
Extension functions: Lambdas with inline
inline fun String.printWithCondition(predicate: (s: String) -> Boolean) {
if (predicate(this)) {
println(this)
}
}
val text = "Hello"
text.printWithCondition { it == "Hello" }
String text = "Hello";
if(Intrinsics.areEqual(text, "Hello")) {
System.out.println(text);
}
Extension functions: AutoCloseable
val fos = FileOutputStream("data.txt")
val result = fos.use {
// do some stuff with stream
"result"
}
println(result)
val resultSet: ResultSet? = ...
resultSet?.use {
println(it.getString(USER_ID))
}
Extension functions: Collections
val list = listOf("Foo", "Bar", "Buzz")
list.filter { it.startsWith("B") } // [Bar, Buzz]
list.map { it.toUpperCase() } // [FOO, BAR, BUZZ]
list.flatMap { it.asIterable() } // [F, o, o, B, a, r, B, u, z, z]
list.groupBy { it.first() } // {F=[Foo], B=[Bar, Buzz]}
list.fold(0, { acc, s -> acc + s.length }) // 10
list.reduce { acc, s -> s + acc } // BuzzBarFoo
Extension functions: Collections
1. Immutable by default.
2. Mutable collections should be created explicitly, e.g. by mutableListOf(),
mutableSetOf(), mutableMapOf() or using constructors.
3. Not lazy by default: each transformation → new collection.
4. Sequences are lazy like a Java 8 Streams. No parallelism.
5. Default implementations: ArrayList, HashSet and HashMap.
6. Array supports same functional operators.
Extension functions: Lambda Extensions
inline fun String.printWithCondition(predicate: String.() -> Boolean) {
if (predicate()) { // predicate(this)
println(this)
}
}
val text = "Hello"
text.printWithCondition { length > 3 }
Extension functions: Standard functions
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
val user = User().apply {
id = 1L
name = "John Smith"
}
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
user?.let {
println(user.name)
}
Conclusion: tools
1. Dagger 2, Butterknife, RxJava 2, Retrofit 2, Realm, Room...
2. Built-in plugin in AS 3.0.
3. Static analysis - https://github.com/arturbosch/detekt.
4. https://kotlinlang.org/docs/reference/coding-conventions.html.
5. Proguard - ok.
6. Debugging - as java.
7. Compile speed - as java - https://habrahabr.ru/company/badoo/blog/329026/.
8. Java projects: Spring 5, Reactor, Corda, Gradle, Spark.
9. Android projects: Hotellook, Avito.
Conclusion: next
1. Intro to Kotlin at Google IO 17: https://youtu.be/X1RVYt2QKQE.
2. Jake Wharton and Christina Lee at Google IO 17:
https://youtu.be/fPzxfeDJDzY.
3. https://developer.android.com/kotlin/index.html.
4. https://kotlinlang.org/docs/reference/.
5. 10 Kotlin Tricks in 10 ish minutes by Jake Wharton:
https://youtu.be/0sPzDwS55wM.
6. Kotlin in Action: https://www.manning.com/books/kotlin-in-action.
7. Kotlin type system: http://natpryce.com/articles/000818.html.
8. Perfomance: https://goo.gl/J2FVSm and https://goo.gl/CDKxw9.
Conclusion: community
1. https://t.me/kotlin_lang @kotlin_lang.
2. http://slack.kotlinlang.org/.
3. http://www.kotlinweekly.net/.

More Related Content

What's hot

Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheeltcurdt
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug Hawkins
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
Java performance
Java performanceJava performance
Java performanceSergey D
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languagesRafael Winterhalter
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlinSergey Bandysik
 
Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monadJarek Ratajski
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습DoHyun Jung
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 

What's hot (20)

Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 
Kotlin meets Gadsu
Kotlin meets GadsuKotlin meets Gadsu
Kotlin meets Gadsu
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Java performance
Java performanceJava performance
Java performance
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlin
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
Java byte code in practice
Java byte code in practiceJava byte code in practice
Java byte code in practice
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Akka in-action
Akka in-actionAkka in-action
Akka in-action
 

Similar to Боремся с NPE вместе с Kotlin, Павел Шацких СберТех

A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin XPeppers
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
KotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptxKotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptxIan Robertson
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with AndroidKurt Renzo Acosta
 

Similar to Боремся с NPE вместе с Kotlin, Павел Шацких СберТех (20)

A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
KotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptxKotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptx
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Java vs kotlin
Java vs kotlinJava vs kotlin
Java vs kotlin
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 

More from Сбертех | SberTech

Есть ли жизнь без Dagger'a, Михаил Крестьянинов Avito
Есть ли жизнь без Dagger'a, Михаил Крестьянинов AvitoЕсть ли жизнь без Dagger'a, Михаил Крестьянинов Avito
Есть ли жизнь без Dagger'a, Михаил Крестьянинов AvitoСбертех | SberTech
 
Feature toggles в процессе подбора, Алексей Ульенков СберТех
Feature toggles в процессе подбора, Алексей Ульенков СберТехFeature toggles в процессе подбора, Алексей Ульенков СберТех
Feature toggles в процессе подбора, Алексей Ульенков СберТехСбертех | SberTech
 
Чистая архитектура, Артур Бадретдинов АБЦТ
Чистая архитектура, Артур Бадретдинов АБЦТЧистая архитектура, Артур Бадретдинов АБЦТ
Чистая архитектура, Артур Бадретдинов АБЦТСбертех | SberTech
 
Модульная архитектура Сбербанк Онлайн, Владимир Озеров и Александр Черушнико...
Модульная архитектура Сбербанк Онлайн, Владимир Озеров и Александр Черушнико...Модульная архитектура Сбербанк Онлайн, Владимир Озеров и Александр Черушнико...
Модульная архитектура Сбербанк Онлайн, Владимир Озеров и Александр Черушнико...Сбертех | SberTech
 
Один день из жизни iOs разработчика, Александр Сычёв Rambler&Co
Один день из жизни iOs разработчика, Александр Сычёв Rambler&CoОдин день из жизни iOs разработчика, Александр Сычёв Rambler&Co
Один день из жизни iOs разработчика, Александр Сычёв Rambler&CoСбертех | SberTech
 
Аспекты применения Agile для крупных хранилищ данных
Аспекты применения Agile для крупных хранилищ данных Аспекты применения Agile для крупных хранилищ данных
Аспекты применения Agile для крупных хранилищ данных Сбертех | SberTech
 
самое интересное в мире блокчейн, опыт и рецепты от сбербанка
самое интересное в мире блокчейн, опыт и рецепты от сбербанкасамое интересное в мире блокчейн, опыт и рецепты от сбербанка
самое интересное в мире блокчейн, опыт и рецепты от сбербанкаСбертех | SberTech
 
Подходы к построению хранилищ данных в крупных организациях
Подходы к построению хранилищ данных в крупных организацияхПодходы к построению хранилищ данных в крупных организациях
Подходы к построению хранилищ данных в крупных организацияхСбертех | SberTech
 

More from Сбертех | SberTech (11)

Есть ли жизнь без Dagger'a, Михаил Крестьянинов Avito
Есть ли жизнь без Dagger'a, Михаил Крестьянинов AvitoЕсть ли жизнь без Dagger'a, Михаил Крестьянинов Avito
Есть ли жизнь без Dagger'a, Михаил Крестьянинов Avito
 
Feature toggles в процессе подбора, Алексей Ульенков СберТех
Feature toggles в процессе подбора, Алексей Ульенков СберТехFeature toggles в процессе подбора, Алексей Ульенков СберТех
Feature toggles в процессе подбора, Алексей Ульенков СберТех
 
Чистая архитектура, Артур Бадретдинов АБЦТ
Чистая архитектура, Артур Бадретдинов АБЦТЧистая архитектура, Артур Бадретдинов АБЦТ
Чистая архитектура, Артур Бадретдинов АБЦТ
 
Модульная архитектура Сбербанк Онлайн, Владимир Озеров и Александр Черушнико...
Модульная архитектура Сбербанк Онлайн, Владимир Озеров и Александр Черушнико...Модульная архитектура Сбербанк Онлайн, Владимир Озеров и Александр Черушнико...
Модульная архитектура Сбербанк Онлайн, Владимир Озеров и Александр Черушнико...
 
Один день из жизни iOs разработчика, Александр Сычёв Rambler&Co
Один день из жизни iOs разработчика, Александр Сычёв Rambler&CoОдин день из жизни iOs разработчика, Александр Сычёв Rambler&Co
Один день из жизни iOs разработчика, Александр Сычёв Rambler&Co
 
Аспекты применения Agile для крупных хранилищ данных
Аспекты применения Agile для крупных хранилищ данных Аспекты применения Agile для крупных хранилищ данных
Аспекты применения Agile для крупных хранилищ данных
 
Internet of things
Internet of thingsInternet of things
Internet of things
 
Биометрия и платежи
Биометрия и платежиБиометрия и платежи
Биометрия и платежи
 
самое интересное в мире блокчейн, опыт и рецепты от сбербанка
самое интересное в мире блокчейн, опыт и рецепты от сбербанкасамое интересное в мире блокчейн, опыт и рецепты от сбербанка
самое интересное в мире блокчейн, опыт и рецепты от сбербанка
 
Подходы к построению хранилищ данных в крупных организациях
Подходы к построению хранилищ данных в крупных организацияхПодходы к построению хранилищ данных в крупных организациях
Подходы к построению хранилищ данных в крупных организациях
 
Blockchain
BlockchainBlockchain
Blockchain
 

Recently uploaded

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Боремся с NPE вместе с Kotlin, Павел Шацких СберТех

  • 1. Better Apps with Kotlin! Pavel Shackih, SBT t.me/PavelShackih
  • 2. Motivation Android core app quality: the app does not crash, force close, freeze, or otherwise function abnormally on any targeted device.
  • 3. Motivation Android core app quality: the app does not crash, force close, freeze, or otherwise function abnormally on any targeted device.
  • 4. JSR-305, Android Support Annotations @Nonnull @Override public User save(@Nonnull User user) { // ... userDao.save(user); // ... return user; }
  • 5. JSR-305, Android Support Annotations 1. Hard to maintain. 2. Verbose, but could be simplified using @ParametersAreNonnullByDefault or @ParametersAreNullableByDefault. 3. Just warning. 4. “Leak” NPE. 5. ~6500 in SBOL.
  • 6. Optional<T> @Override public Optional<User> findById(long id) { return Optional.ofNullable(userDao.findById(id)); } public void printUser(long id) { Optional<User> optional = findById(id); optional.ifPresent(user -> System.out.println(user)); }
  • 7. Optional<T> 1. Verbose. 2. GC overhead. 3. Problem with third-party libraries.
  • 8.
  • 9. Here comes Kotlin fun main(args: Array<String>) { val hello = "Hello, Innopolis!" println(hello) }
  • 10. Here comes Kotlin ● statically-typed, object-oriented, functional; ● target: JVM, Android, JS, Native (in progress); ● fully interoperable with Java; ● compact runtime lib, good tooling; ● runs as fast as an equivalent on Java; ● easy to learn for Java developers; ● official Android development language.
  • 11. Not nullable types by default var foo: String = "Foo" // var foo = "Foo" foo = null // Compile error: Null can not be a value of a non-null type String var bar: String? = "Bar" bar = null // Ok bar = foo // Ok foo = bar // Error
  • 12. Not nullable types by default String String? String? = String or null
  • 13. Deal with nullable types val user: User? = null println(user.address.street) // Error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type kotlin.String?
  • 14. Smartcast val user: User? = null if (user != null && user.address != null) { println(user.address.street) // Now: user: User, address: Address } User? User Address? Address
  • 15. Safe call operator ?. val user: User? = null println(user?.address) if (user != null) { return user.getAddress(); } else { return null; } user?.address user.address null *Kotlin in Action user != null user == null Safe call operator always returns nullable type of <T>, so <T> result type transform to type <T?> println(user?.address?.street) Chaining safe call operators:
  • 16. Elvis operator ?: val user: User? = null println(user ?: ADMIN) if (user != null) { return user; } else { return ADMIN; } user user ADMIN *Kotlin in Action user != null user == null println(user?.address?.street ?: UNKNOWN_STREET)
  • 17. Let function val user: User? = null user?.let { println(it) } if (user != null) { System.out.println(user); } user println(user) user != null *Kotlin in Action
  • 18. Not null assertions: !! operator val user: User? = null println(user!!.address) System.out.println(user.getAddress()); user user.address NullPointerException *Kotlin in Action user != null user == null
  • 19. Platform types and Java interoperability Java Kotlin @Nullable + String String? @NotNull + String String String String! String! = String or String? val stringValue = Java.getString() println(stringValue.length) // Ok println(stringValue?.length) // Ok
  • 20. Kotlin nullability: Examples class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) val id = savedInstanceState.getString(ID) // compile error } } class MyIntentService : IntentService("MyIntentService") { override fun onHandleIntent(intent: Intent?) { val param1 = intent.getStringExtra(EXTRA_PARAM1) // compile error } }
  • 21. Intrinsics ● Apply Intrinsics.checkParameterIsNotNull() for every public function for each non-null parameter. ● Disable using -Xno-param-assertions or Proguard. JDK 1.8 Kotlin @Override public void forEachRemaining(DoubleConsumer action) { Objects.requireNonNull(action); if (count == -2) { action.accept(first); count = -1; } } @NotNull public User save(@NotNull User user) { Intrinsics.checkParameterIsNotNull(user, "user"); this.userDao.save(user); return user; }
  • 22. Kotlin nullability 1. Hard to maintain built-in type system. 2. Verbose special syntax for nullable values. 3. Not error, just a warning, no guarantees compile time error. 4. “Leak” NPE kotlin intrinsics. 5. GC overhead no overhead at all. 6. Problem with third-party libraries kotlin compiler could read default java annotations from external byte code.
  • 23. Extension functions Java Kotlin public static boolean isEmpty(@Nullable String string) { return string == null || string.isEmpty(); } fun String?.isEmpty(): Boolean { return this == null || this.length == 0 } String text = ...; if (isEmpty(text)) { System.out.println("Empty text!"); } val text = ... if (text.isEmpty()) { println("Empty text!") }
  • 24. Extension functions: Lambdas fun String.printWithCondition(predicate: (s: String) -> Boolean) { if (predicate(this)) { println(this) } } val text = "Hello" text.printWithCondition { it == "Hello" }
  • 25. Extension functions: Lambdas with inline inline fun String.printWithCondition(predicate: (s: String) -> Boolean) { if (predicate(this)) { println(this) } } val text = "Hello" text.printWithCondition { it == "Hello" } String text = "Hello"; if(Intrinsics.areEqual(text, "Hello")) { System.out.println(text); }
  • 26. Extension functions: AutoCloseable val fos = FileOutputStream("data.txt") val result = fos.use { // do some stuff with stream "result" } println(result) val resultSet: ResultSet? = ... resultSet?.use { println(it.getString(USER_ID)) }
  • 27. Extension functions: Collections val list = listOf("Foo", "Bar", "Buzz") list.filter { it.startsWith("B") } // [Bar, Buzz] list.map { it.toUpperCase() } // [FOO, BAR, BUZZ] list.flatMap { it.asIterable() } // [F, o, o, B, a, r, B, u, z, z] list.groupBy { it.first() } // {F=[Foo], B=[Bar, Buzz]} list.fold(0, { acc, s -> acc + s.length }) // 10 list.reduce { acc, s -> s + acc } // BuzzBarFoo
  • 28. Extension functions: Collections 1. Immutable by default. 2. Mutable collections should be created explicitly, e.g. by mutableListOf(), mutableSetOf(), mutableMapOf() or using constructors. 3. Not lazy by default: each transformation → new collection. 4. Sequences are lazy like a Java 8 Streams. No parallelism. 5. Default implementations: ArrayList, HashSet and HashMap. 6. Array supports same functional operators.
  • 29. Extension functions: Lambda Extensions inline fun String.printWithCondition(predicate: String.() -> Boolean) { if (predicate()) { // predicate(this) println(this) } } val text = "Hello" text.printWithCondition { length > 3 }
  • 30. Extension functions: Standard functions public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this } val user = User().apply { id = 1L name = "John Smith" } public inline fun <T, R> T.let(block: (T) -> R): R = block(this) user?.let { println(user.name) }
  • 31. Conclusion: tools 1. Dagger 2, Butterknife, RxJava 2, Retrofit 2, Realm, Room... 2. Built-in plugin in AS 3.0. 3. Static analysis - https://github.com/arturbosch/detekt. 4. https://kotlinlang.org/docs/reference/coding-conventions.html. 5. Proguard - ok. 6. Debugging - as java. 7. Compile speed - as java - https://habrahabr.ru/company/badoo/blog/329026/. 8. Java projects: Spring 5, Reactor, Corda, Gradle, Spark. 9. Android projects: Hotellook, Avito.
  • 32. Conclusion: next 1. Intro to Kotlin at Google IO 17: https://youtu.be/X1RVYt2QKQE. 2. Jake Wharton and Christina Lee at Google IO 17: https://youtu.be/fPzxfeDJDzY. 3. https://developer.android.com/kotlin/index.html. 4. https://kotlinlang.org/docs/reference/. 5. 10 Kotlin Tricks in 10 ish minutes by Jake Wharton: https://youtu.be/0sPzDwS55wM. 6. Kotlin in Action: https://www.manning.com/books/kotlin-in-action. 7. Kotlin type system: http://natpryce.com/articles/000818.html. 8. Perfomance: https://goo.gl/J2FVSm and https://goo.gl/CDKxw9.
  • 33. Conclusion: community 1. https://t.me/kotlin_lang @kotlin_lang. 2. http://slack.kotlinlang.org/. 3. http://www.kotlinweekly.net/.