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

Kotlin for android developers whats new

  • 1.
    Why you shouldtry to write app in You really should
  • 2.
  • 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(valid: 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 valx: 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 implementequals() 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 staticsmethods 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 useMutableList<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 propertiessmarter 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 yourmultiple 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 canstart 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 callfunction 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 isnot 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 isnot 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 SerhiiChaban Twitter:@SerhiiChaban Email: serhii.chaban@gmail.com Facebook:serhiichaban