SlideShare a Scribd company logo
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

More Related Content

What's hot

2017: Kotlin - now more than ever
2017: Kotlin - now more than ever2017: Kotlin - now more than ever
2017: Kotlin - now more than ever
Kai Koenig
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
Arnaud 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 2017
Arnaud Giuliani
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
Andrzej Sitek
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
Ciro 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 2017
Arnaud Giuliani
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
Bartosz 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 developers
Bartosz Kosarzycki
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
intelliyole
 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1
Mohamed Nabil, MSc.
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
Arnaud Giuliani
 
BangaloreJUG introduction to kotlin
BangaloreJUG   introduction to kotlinBangaloreJUG   introduction to kotlin
BangaloreJUG introduction to kotlin
Chandra 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 Kotlin
Kai 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 bootcamp
Kai 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 - 3
Mohamed 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 Blueprint
Kai Koenig
 

What's hot (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
 

Similar to K is for Kotlin

Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
VMware Tanzu
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
Shaul Rosenzwieg
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
Kurt Renzo Acosta
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael 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
STX Next
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
Minseo Chayabanjonglerd
 
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
Codemotion
 
Kotlin
KotlinKotlin
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 Patterns
Stefano Fago
 
Scala ntnu
Scala ntnuScala ntnu
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
JyothiAmpally
 
Collections
CollectionsCollections
Collections
sagsharma
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
Łukasz Wójcik
 
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 Javascript
Julie Iskander
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
Teksify
 

Similar to 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
 

More from TechMagic

Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.js
TechMagic
 
Android notifications. testing guideline
Android notifications. testing guidelineAndroid notifications. testing guideline
Android notifications. testing guideline
TechMagic
 
Coaching
CoachingCoaching
Coaching
TechMagic
 
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 Stripe
TechMagic
 
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 customer
TechMagic
 
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
TechMagic
 
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
 
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
 

More from 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)
 

Recently uploaded

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 

Recently uploaded (20)

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a 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