SlideShare une entreprise Scribd logo
1  sur  33
K is for Kotlin
Roman Ursu
Introduction
Kotlin is a JVM based language developed by JetBrains.
Kotlin was created with Java developers in mind and these are two very interesting
features for Android developers:
● Kotlin is very intuitive and easy to learn for Java developers
● We have total integration with Android Studio
Introduction
● It’s more expressive (You can write more with much less code)
● It’s safer (Kotlin is null safe)
● It’s functional (lambda expressions, the way it deals with collections)
● It makes use of extension functions
● It’s highly interoperable (you can continue using most libraries and code written
in Java, It’s even possible to create mixed projects)
Few facts
● Compatibility: Kotlin is fully compatible with JDK 6, fully supported in Android
Studio and compatible with the Android build system.
● Performance: A Kotlin application runs as fast as an equivalent Java one, thanks
to very similar bytecode structure.
● Interoperability: Kotlin is 100% interoperable with Java, allowing to use all
existing Android libraries in a Kotlin application.
● Footprint: Kotlin has a very compact runtime library. Kotlin runtime adds only a
few hundred methods.
● Compilation Time: Kotlin supports efficient incremental compilation.
Configuring Gradle
buildscript {
ext.kotlin_version = '1.1.3-2'
ext.support_version = '25.3.1'
ext.anko_version = '0.9'
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha7'
classpath "org.jetbrains.kotlin:kotlin-gradle-
plugin:$kotlin_version"
}
}
...
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
Android Studio Support
Converting Java code to Kotlin.
public class KotlinExampleApp extends Application {
public static KotlinExampleApp app;
private AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
app = KotlinExampleApp.this;
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.netModule(new NetModule())
.weatherModule(new WeatherModule())
.build();
}
public AppComponent getAppComponent() {
return appComponent;
}
}
class KotlinExampleApp : Application() {
var appComponent: AppComponent? = null
private set
companion object {
var app: KotlinExampleApp
}
override fun onCreate() {
super.onCreate()
app = this@KotlinExampleApp
appComponent =
DaggerAppComponent.builder()
.appModule(AppModule(this))
.netModule(NetModule())
.weatherModule(WeatherModule())
.build()
}
}
class KotlinExampleApp : Application() {
var appComponent: AppComponent? = null
private set
companion object {
var app: KotlinExampleApp? = null
}
override fun onCreate() {
super.onCreate()
app = this@KotlinExampleApp
appComponent = DaggerAppComponent.builder()
.appModule(AppModule(this))
.netModule(NetModule())
.weatherModule(WeatherModule())
.build()
}
}
Classes declaration
By default, a class always extends from Any (similar to Java Object), but we can extend
any other classes.
open class Animal(name: String)
class Person(firstName: String, lastName: String) : Animal(firstName)
class Customer(val customerName: String = "defaultName") // default
value
Instantiation
val customer = Customer("Joe Smith")
Constructors
class Person constructor(firstName: String) {}
class Person(firstName: String) {}
class Customer(name: String) {
init {
logger.info("Customer initialized with value ${name}")
}
}
class Customer(name: String) {
val customerKey = name.toUpperCase()
}
class Person(val firstName: String, val
lastName: String, var age: Int) { }
class Person(val name: String) {
constructor(name: String, parent: Person) :
this(name) {
parent.children.add(this)
}
}
Inheritance (Overriding Methods)
open class Base {
open fun v() {}
fun nv() {}
}
class Derived() : Base() {
override fun v() {}
}
open class AnotherDerived() : Base() {
final override fun v() {}
}
Inheritance
open class A {
open fun f() { print("A") }
fun a() { print("a") }
}
interface B {
fun f() { print("B") } // interface members are 'open' by default
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()
}
}
“Static methods”
There are No static methods in Kotlin.
In most cases, it's recommended to simply use package-level functions instead.
Companion object inside your class will make you able to call its members with the
same syntax as calling static methods in Java.
class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
}
...
val instance = MyClass.create()
Basic Types
● Basic types such as integers, floats, characters or booleans still exist, but
they all act as an object
● There are no automatic conversions among numeric types
● Characters (Char) cannot directly be used as numbers. (use *.toInt())
● Bitwise arithmetical operations are a bit different. (“and” instead of “&”, “or”
instead of “|”)
● It's common practice in Kotlin is to omit variable types
● A String can be accessed as an array and can be iterated
Variables and Constants
var str = "String" // A String
var number = 25 //An Int
val a: Int = 23
val c: Context = activity
Properties
public class Person {
var name: String = ""
get() = field.toUpperCase()
private set(value) {
field = "Name: $value"
}
//...
}
Methods
private fun method1(a: Int): Int {
return a * a
}
private fun method2(a: Int): Int = a * a
private fun method3(a: Int) = a * a
private fun doSmth(): Unit {/* nothing here */}
Extension functions
● adds a new behaviour to a class
● even if we don’t have access to the source code
● we don’t need to pass the object as an argument
● we can implement it using this and all its public methods
fun Context.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, message, duration).show()
}
Usage
toast("Hello world!")
toast("Hello world!", Toast.LENGTH_LONG)
Data Classes
● Avoid the boilerplate we need in Java to create POJO
● They usually only provide plain getters and setters to access to their fields
● We get equals(), hashCode(), copy() for free
data class Forecast(
@SerializedName("date") val date: Date,
@SerializedName("temp") val temperature: Float,
@SerializedName("desc") val description: String) // that’s all the declaration
// copy but change smth
val f1 = Forecast(Date(), 27.5f, "Storming")
val f2 = f1.copy(temperature = 31f)
Declaration Destructuring
val f1 = Forecast(Date(), 27.7f, "Shiny day")
val (date, temperature, details) = f1
...
val otherVariable = date
val otherTemperature = temperature
for ((key, value) in map) {
Log.d("map", "key:$key, value:$value")
}
With
With allow you to use public functions and properties without specifying variable.
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
with(items[position]) { // WeatherDataDto object contains props temperature, humidity etc
holder!!.temperature!!.text = temperature.toString()
holder.humidity!!.text = humidity.toString()
holder.description!!.text = description
holder.windSpeed!!.text = windSpeed.toString()
Glide.with(this@MainActivity).load(iconUrl).into(holder.icon)
}
holder!!.itemView.setOnClickListener { itemClick(items[position]) }
}
Lambdas
Lambda expression is a simple way to define an anonymous function. Function that
receives an interface with a single function can be substituted by a lambda.
Before
public interface OnClickListener { void onClick(View v) }
...
view.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(v.getContext(), "Click", Toast.LENGTH_SHORT).show();
} });
Now
fun setOnClickListener(listener: (View) -> Unit)
...
view.setOnClickListener({ view -> toast("Click")})
// can be simplified to
view.setOnClickListener { toast("Click") }
Collections
Immutable
Iterable
Collection
List
Set
Map
Mutable
MutableIterable
MutableCollection
MutableList
MutableSet
MutableMap
We can use Java collections, but Kotlin provides a good set of native interfaces:
Functional operations
any (Returns true if at least one element matches the given predicate)
val list = listOf(1, 2, 3, 4, 5, 6)
assertTrue(list.any { it % 2 == 0 })
all (Returns true if all the elements match the given predicate)
assertTrue(list.all { it < 10 })
count (Returns the number of elements matching the given predicate)
assertEquals(3, list.count { it % 2 == 0 })
fold (Accumulates the value starting with an initial value and applying an operation from the first to the
last element in a collection)
assertEquals(25, list.fold(4) { total, next -> total + next })
forEachIndexed (Same as forEach, though we also get the index of the element)
list.forEachIndexed { index, value -> println("position $index contains a $value") }
Functional operations
dropWhile
Returns a list containing all elements except first elements that satisfy the given predicate.
assertEquals(listOf(3, 4, 5, 6), list.dropWhile { it < 3 })
filter
Returns a list containing all elements matching the given predicate.
assertEquals(listOf(2, 4, 6), list.filter { it % 2 == 0 })
take
Returns a list containing first n elements.
assertEquals(listOf(1, 2), list.take(2))
groupBy
Returns a map of the elements in original collection grouped by the result of given function
assertEquals(mapOf("odd" to listOf(1, 3, 5), "even" to listOf(2, 4, 6)), list.groupBy { if (it % 2 == 0) "even"
else "odd" })
Functional operations
elementAtOrNull
Returns an element at the given index or null if the index is out of bounds of this collection.
assertNull(list.elementAtOrNull(10))
sortBy
Returns a list of all elements, sorted by the specified comparator.
assertEquals(listOf(3, 7, 2, 5), unsortedList.sortBy { it % 3 })
plus
Returns a list containing all elements of the original collection and then all elements of the given
collection. Because of the name of the function, we can use the ‘+’ operator with it.
assertEquals(listOf(1, 2, 3, 4, 5, 6, 7, 8), list + listOf(7, 8))
And many more
Null safety in Kotlin
Being null considered the billion-dollar mistake by its own creator (Tony Hoare)
// this is Java and it will compile
Forecast forecast = null;
forecast.toString();
// this is Kotlin and it won’t compile
val forecast: Forecast? = null
forecast.toString()
// use !! if you a sure that this can’t be null
forecast!!.toString();
// use ?. if you hesitate
forecast?.toString();
Lazy
If you don’t want to declare variable as nullable but you can’t initialize it in
constructor use lateinit
class App : Application() {
companion object {
lateinit var instance: App
}
overrride fun onCreate() {
super.onCreate()
instance = this
}
}
Flow control (IF)
In Kotlin, if is an expression, i.e. it returns a value.
if branches can be blocks, and the last expression is the value of a block:
val max = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}
Flow control (WHEN)
when replaces the switch operator of C-like languages. In the simplest form
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
when {
x.isOdd() -> print("odd")
x.isEven() -> print("even")
else -> print("x is weird")
}
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("outside the range")
else -> print("none of the above")
}
For Loops
for iterates through anything that provides an iterator
for (item in collection) print(item)
for (i in array.indices) {
print(array[i])
}
for ((index, value) in array.withIndex()) {
println("at $index is $value")
}
Inconveniences
Code completion (variables declaration)
Java case
You need only type class name and
variable name comes by itself :)
Kotlin case
You should type everything :(
Inconveniences
Code completion (in RxJava)
Java case
Inconveniences
Code completion (in RxJava)
Kotlin case
I need some hint... and I don’t want to search what T means!!! >:(
Thank you for attention

Contenu connexe

Tendances

2017: Kotlin - now more than ever
2017: Kotlin - now more than ever2017: Kotlin - now more than ever
2017: Kotlin - now more than everKai Koenig
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
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
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
 
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 hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Arnaud Giuliani
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Mohamed Nabil, MSc.
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
 
BangaloreJUG introduction to kotlin
BangaloreJUG   introduction to kotlinBangaloreJUG   introduction to kotlin
BangaloreJUG introduction to kotlinChandra Sekhar Nayak
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinKai Koenig
 
Summer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcampSummer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcampKai Koenig
 
Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?Kai Koenig
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
API management with Taffy and API Blueprint
API management with Taffy and API BlueprintAPI management with Taffy and API Blueprint
API management with Taffy and API BlueprintKai Koenig
 

Tendances (19)

2017: Kotlin - now more than ever
2017: Kotlin - now more than ever2017: Kotlin - now more than ever
2017: Kotlin - now more than ever
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
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
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
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 hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
BangaloreJUG introduction to kotlin
BangaloreJUG   introduction to kotlinBangaloreJUG   introduction to kotlin
BangaloreJUG introduction to kotlin
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with Kotlin
 
Summer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcampSummer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcamp
 
Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?Anko - The Ultimate Ninja of Kotlin Libraries?
Anko - The Ultimate Ninja of Kotlin Libraries?
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
API management with Taffy and API Blueprint
API management with Taffy and API BlueprintAPI management with Taffy and API Blueprint
API management with Taffy and API Blueprint
 

Similaire à K is for Kotlin

Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with AndroidKurt Renzo Acosta
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016STX Next
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Codemotion
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers STX Next
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 

Similaire à K is for Kotlin (20)

Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
 
Kotlin
KotlinKotlin
Kotlin
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Collections
CollectionsCollections
Collections
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 

Plus de TechMagic

Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.jsTechMagic
 
Android notifications. testing guideline
Android notifications. testing guidelineAndroid notifications. testing guideline
Android notifications. testing guidelineTechMagic
 
Angular 2 vs React. What to chose in 2017?
Angular 2 vs React. What to chose in 2017?Angular 2 vs React. What to chose in 2017?
Angular 2 vs React. What to chose in 2017?TechMagic
 
Getting started with Stripe
Getting started with StripeGetting started with Stripe
Getting started with StripeTechMagic
 
Android developer options &amp; android sdk tools (for qa)
Android developer options &amp; android sdk tools (for qa)Android developer options &amp; android sdk tools (for qa)
Android developer options &amp; android sdk tools (for qa)TechMagic
 
Tips and Tricks for email communication with customer
Tips and Tricks for email communication with customerTips and Tricks for email communication with customer
Tips and Tricks for email communication with customerTechMagic
 
Test Driven Development in Node.js apps
Test Driven Development in Node.js appsTest Driven Development in Node.js apps
Test Driven Development in Node.js appsTechMagic
 
OS X Server as CI for iOS
OS X Server as CI for iOSOS X Server as CI for iOS
OS X Server as CI for iOSTechMagic
 
TechMagic - Development Studio for Startups (iOS, Android, Node.js)
TechMagic - Development Studio for Startups (iOS, Android, Node.js)TechMagic - Development Studio for Startups (iOS, Android, Node.js)
TechMagic - Development Studio for Startups (iOS, Android, Node.js)TechMagic
 

Plus de TechMagic (10)

Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.js
 
Android notifications. testing guideline
Android notifications. testing guidelineAndroid notifications. testing guideline
Android notifications. testing guideline
 
Coaching
CoachingCoaching
Coaching
 
Angular 2 vs React. What to chose in 2017?
Angular 2 vs React. What to chose in 2017?Angular 2 vs React. What to chose in 2017?
Angular 2 vs React. What to chose in 2017?
 
Getting started with Stripe
Getting started with StripeGetting started with Stripe
Getting started with Stripe
 
Android developer options &amp; android sdk tools (for qa)
Android developer options &amp; android sdk tools (for qa)Android developer options &amp; android sdk tools (for qa)
Android developer options &amp; android sdk tools (for qa)
 
Tips and Tricks for email communication with customer
Tips and Tricks for email communication with customerTips and Tricks for email communication with customer
Tips and Tricks for email communication with customer
 
Test Driven Development in Node.js apps
Test Driven Development in Node.js appsTest Driven Development in Node.js apps
Test Driven Development in Node.js apps
 
OS X Server as CI for iOS
OS X Server as CI for iOSOS X Server as CI for iOS
OS X Server as CI for iOS
 
TechMagic - Development Studio for Startups (iOS, Android, Node.js)
TechMagic - Development Studio for Startups (iOS, Android, Node.js)TechMagic - Development Studio for Startups (iOS, Android, Node.js)
TechMagic - Development Studio for Startups (iOS, Android, Node.js)
 

Dernier

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
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
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging 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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Dernier (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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 ...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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?
 
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
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
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...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

K is for Kotlin

  • 1. K is for Kotlin Roman Ursu
  • 2. Introduction Kotlin is a JVM based language developed by JetBrains. Kotlin was created with Java developers in mind and these are two very interesting features for Android developers: ● Kotlin is very intuitive and easy to learn for Java developers ● We have total integration with Android Studio
  • 3. Introduction ● It’s more expressive (You can write more with much less code) ● It’s safer (Kotlin is null safe) ● It’s functional (lambda expressions, the way it deals with collections) ● It makes use of extension functions ● It’s highly interoperable (you can continue using most libraries and code written in Java, It’s even possible to create mixed projects)
  • 4. Few facts ● Compatibility: Kotlin is fully compatible with JDK 6, fully supported in Android Studio and compatible with the Android build system. ● Performance: A Kotlin application runs as fast as an equivalent Java one, thanks to very similar bytecode structure. ● Interoperability: Kotlin is 100% interoperable with Java, allowing to use all existing Android libraries in a Kotlin application. ● Footprint: Kotlin has a very compact runtime library. Kotlin runtime adds only a few hundred methods. ● Compilation Time: Kotlin supports efficient incremental compilation.
  • 5. Configuring Gradle buildscript { ext.kotlin_version = '1.1.3-2' ext.support_version = '25.3.1' ext.anko_version = '0.9' repositories { jcenter() maven { url 'https://maven.google.com' } } dependencies { classpath 'com.android.tools.build:gradle:3.0.0-alpha7' classpath "org.jetbrains.kotlin:kotlin-gradle- plugin:$kotlin_version" } } ... apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt'
  • 6. Android Studio Support Converting Java code to Kotlin. public class KotlinExampleApp extends Application { public static KotlinExampleApp app; private AppComponent appComponent; @Override public void onCreate() { super.onCreate(); app = KotlinExampleApp.this; appComponent = DaggerAppComponent.builder() .appModule(new AppModule(this)) .netModule(new NetModule()) .weatherModule(new WeatherModule()) .build(); } public AppComponent getAppComponent() { return appComponent; } } class KotlinExampleApp : Application() { var appComponent: AppComponent? = null private set companion object { var app: KotlinExampleApp } override fun onCreate() { super.onCreate() app = this@KotlinExampleApp appComponent = DaggerAppComponent.builder() .appModule(AppModule(this)) .netModule(NetModule()) .weatherModule(WeatherModule()) .build() } } class KotlinExampleApp : Application() { var appComponent: AppComponent? = null private set companion object { var app: KotlinExampleApp? = null } override fun onCreate() { super.onCreate() app = this@KotlinExampleApp appComponent = DaggerAppComponent.builder() .appModule(AppModule(this)) .netModule(NetModule()) .weatherModule(WeatherModule()) .build() } }
  • 7. Classes declaration By default, a class always extends from Any (similar to Java Object), but we can extend any other classes. open class Animal(name: String) class Person(firstName: String, lastName: String) : Animal(firstName) class Customer(val customerName: String = "defaultName") // default value Instantiation val customer = Customer("Joe Smith")
  • 8. Constructors class Person constructor(firstName: String) {} class Person(firstName: String) {} class Customer(name: String) { init { logger.info("Customer initialized with value ${name}") } } class Customer(name: String) { val customerKey = name.toUpperCase() } class Person(val firstName: String, val lastName: String, var age: Int) { } class Person(val name: String) { constructor(name: String, parent: Person) : this(name) { parent.children.add(this) } }
  • 9. Inheritance (Overriding Methods) open class Base { open fun v() {} fun nv() {} } class Derived() : Base() { override fun v() {} } open class AnotherDerived() : Base() { final override fun v() {} }
  • 10. Inheritance open class A { open fun f() { print("A") } fun a() { print("a") } } interface B { fun f() { print("B") } // interface members are 'open' by default 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() } }
  • 11. “Static methods” There are No static methods in Kotlin. In most cases, it's recommended to simply use package-level functions instead. Companion object inside your class will make you able to call its members with the same syntax as calling static methods in Java. class MyClass { companion object Factory { fun create(): MyClass = MyClass() } } ... val instance = MyClass.create()
  • 12. Basic Types ● Basic types such as integers, floats, characters or booleans still exist, but they all act as an object ● There are no automatic conversions among numeric types ● Characters (Char) cannot directly be used as numbers. (use *.toInt()) ● Bitwise arithmetical operations are a bit different. (“and” instead of “&”, “or” instead of “|”) ● It's common practice in Kotlin is to omit variable types ● A String can be accessed as an array and can be iterated
  • 13. Variables and Constants var str = "String" // A String var number = 25 //An Int val a: Int = 23 val c: Context = activity
  • 14. Properties public class Person { var name: String = "" get() = field.toUpperCase() private set(value) { field = "Name: $value" } //... }
  • 15. Methods private fun method1(a: Int): Int { return a * a } private fun method2(a: Int): Int = a * a private fun method3(a: Int) = a * a private fun doSmth(): Unit {/* nothing here */}
  • 16. Extension functions ● adds a new behaviour to a class ● even if we don’t have access to the source code ● we don’t need to pass the object as an argument ● we can implement it using this and all its public methods fun Context.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, message, duration).show() } Usage toast("Hello world!") toast("Hello world!", Toast.LENGTH_LONG)
  • 17. Data Classes ● Avoid the boilerplate we need in Java to create POJO ● They usually only provide plain getters and setters to access to their fields ● We get equals(), hashCode(), copy() for free data class Forecast( @SerializedName("date") val date: Date, @SerializedName("temp") val temperature: Float, @SerializedName("desc") val description: String) // that’s all the declaration // copy but change smth val f1 = Forecast(Date(), 27.5f, "Storming") val f2 = f1.copy(temperature = 31f)
  • 18. Declaration Destructuring val f1 = Forecast(Date(), 27.7f, "Shiny day") val (date, temperature, details) = f1 ... val otherVariable = date val otherTemperature = temperature for ((key, value) in map) { Log.d("map", "key:$key, value:$value") }
  • 19. With With allow you to use public functions and properties without specifying variable. override fun onBindViewHolder(holder: ViewHolder?, position: Int) { with(items[position]) { // WeatherDataDto object contains props temperature, humidity etc holder!!.temperature!!.text = temperature.toString() holder.humidity!!.text = humidity.toString() holder.description!!.text = description holder.windSpeed!!.text = windSpeed.toString() Glide.with(this@MainActivity).load(iconUrl).into(holder.icon) } holder!!.itemView.setOnClickListener { itemClick(items[position]) } }
  • 20. Lambdas Lambda expression is a simple way to define an anonymous function. Function that receives an interface with a single function can be substituted by a lambda. Before public interface OnClickListener { void onClick(View v) } ... view.setOnClickListener(new OnClickListener() { public void onClick(View v) { Toast.makeText(v.getContext(), "Click", Toast.LENGTH_SHORT).show(); } }); Now fun setOnClickListener(listener: (View) -> Unit) ... view.setOnClickListener({ view -> toast("Click")}) // can be simplified to view.setOnClickListener { toast("Click") }
  • 22. Functional operations any (Returns true if at least one element matches the given predicate) val list = listOf(1, 2, 3, 4, 5, 6) assertTrue(list.any { it % 2 == 0 }) all (Returns true if all the elements match the given predicate) assertTrue(list.all { it < 10 }) count (Returns the number of elements matching the given predicate) assertEquals(3, list.count { it % 2 == 0 }) fold (Accumulates the value starting with an initial value and applying an operation from the first to the last element in a collection) assertEquals(25, list.fold(4) { total, next -> total + next }) forEachIndexed (Same as forEach, though we also get the index of the element) list.forEachIndexed { index, value -> println("position $index contains a $value") }
  • 23. Functional operations dropWhile Returns a list containing all elements except first elements that satisfy the given predicate. assertEquals(listOf(3, 4, 5, 6), list.dropWhile { it < 3 }) filter Returns a list containing all elements matching the given predicate. assertEquals(listOf(2, 4, 6), list.filter { it % 2 == 0 }) take Returns a list containing first n elements. assertEquals(listOf(1, 2), list.take(2)) groupBy Returns a map of the elements in original collection grouped by the result of given function assertEquals(mapOf("odd" to listOf(1, 3, 5), "even" to listOf(2, 4, 6)), list.groupBy { if (it % 2 == 0) "even" else "odd" })
  • 24. Functional operations elementAtOrNull Returns an element at the given index or null if the index is out of bounds of this collection. assertNull(list.elementAtOrNull(10)) sortBy Returns a list of all elements, sorted by the specified comparator. assertEquals(listOf(3, 7, 2, 5), unsortedList.sortBy { it % 3 }) plus Returns a list containing all elements of the original collection and then all elements of the given collection. Because of the name of the function, we can use the ‘+’ operator with it. assertEquals(listOf(1, 2, 3, 4, 5, 6, 7, 8), list + listOf(7, 8)) And many more
  • 25. Null safety in Kotlin Being null considered the billion-dollar mistake by its own creator (Tony Hoare) // this is Java and it will compile Forecast forecast = null; forecast.toString(); // this is Kotlin and it won’t compile val forecast: Forecast? = null forecast.toString() // use !! if you a sure that this can’t be null forecast!!.toString(); // use ?. if you hesitate forecast?.toString();
  • 26. Lazy If you don’t want to declare variable as nullable but you can’t initialize it in constructor use lateinit class App : Application() { companion object { lateinit var instance: App } overrride fun onCreate() { super.onCreate() instance = this } }
  • 27. Flow control (IF) In Kotlin, if is an expression, i.e. it returns a value. if branches can be blocks, and the last expression is the value of a block: val max = if (a > b) { print("Choose a") a } else { print("Choose b") b }
  • 28. Flow control (WHEN) when replaces the switch operator of C-like languages. In the simplest form when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { print("x is neither 1 nor 2") } } when { x.isOdd() -> print("odd") x.isEven() -> print("even") else -> print("x is weird") } when (x) { in 1..10 -> print("x is in the range") in validNumbers -> print("x is valid") !in 10..20 -> print("outside the range") else -> print("none of the above") }
  • 29. For Loops for iterates through anything that provides an iterator for (item in collection) print(item) for (i in array.indices) { print(array[i]) } for ((index, value) in array.withIndex()) { println("at $index is $value") }
  • 30. Inconveniences Code completion (variables declaration) Java case You need only type class name and variable name comes by itself :) Kotlin case You should type everything :(
  • 32. Inconveniences Code completion (in RxJava) Kotlin case I need some hint... and I don’t want to search what T means!!! >:(
  • 33. Thank you for attention