SlideShare a Scribd company logo
Introduction to Kotlin
Brief intro to the language
What is Kotlin?
“Kotlin is a Concise, Safe and Statically typed programming language focused on
Interoperability with Java.”
● Compiles to JVM bytecode class files
● Generates Java 6, Java 8 or JS compatible bytecode, or LLVM binary
● Has good plugin for IntelliJ and Android Studio
● From Android Studio 3 (currently canary), fully supported out of the box
● A lot of features solve Java pitfalls
Syntax overview
The words “extends” and “implement”
were replaced by a colon “:”
class MainActivity : AppCompatActivity()
Define functions inside our class with the
“fun” keyword and the return type is
added to the end. void is implicit
override fun onCreate(savedState: Bundle?) :Int {
}
fun sum(a: Int, b: Int) = a + b
Bye-bye semicolon: in Kotlin semicolon
is optional
val price = 100
var is a variable. val is a constant
val price = 100 // Int
price = 30 // won't compile! it's a constant
var total = price * 3 // Int
val name = "Shaul haTotach" // String
You can specify the type explicitly:
val lastname : String = "Shaul haGadol"
var size : Double = 30.0
var time : Float = 15f
If you want to init a var later
lateinit var notInited: TextView
Equality
a === b // reference equality
a !== b
a == b // content equality
a != b
Properties are treated like fields
resources.getString(R.string.app_name)
// still allowed:
getResources().getString(R.string.app_name)
Everything is non-nullable implicitly
val a : String = null // won't compile!
val ok : String? = null // OK :)
Safe call
val context : Context? = null
// not crash, res will be null:
val res = context?.getResources()
Non null assertion operator
val context : Context? = null
// Will throw NPE:
val res = context!!.getResources()
Smart cast, why?
//bad way to do it:
val context : Context? = null
val res = context?.getResources()
val appName = res?.getString(R.string.app_name)
val shortName = appName?.substring(0, 2)
Check if it is null and inside of the block
it is considered non-nullable:
val context : Context? = null
if (context != null) {
// Don't need '?' anymore
val res = context.getResources()
val appName = res.getString(R.string.app_name)
val shortName = appName.substring(0, 2)
}
Elvis operator simplified
try {
// code...
} catch (e: Throwable) {
Log.e("TAG", e.message ?: "Error message")
}
Unsafe cast: throws if cast not possible
val bar = findViewById(R.id.bar) as ActionBar
Ranges:
for (i in 1..4) Log.d(TAG, "got $i") // "1234"
for (i in 4 downTo 1) Log.d(TAG, "got $i") // "4321"
for (i in 1..4 step 2) print(i) // "13"
if (i in 1..10) println(i) // 1 <= i && i <= 10
When:
when (x) {
1 -> Log.d("tag", "one")
2 -> Log.d("tag", "two")
else -> { // Note the block
Log.d("tag", "many")
}
}
Advanced when:
when (x) {
parseInt(s) -> print("s encodes x")
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
When with no clause:
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}
Extension functions
Can extend functionality of a class
without writing a new class
val container : ViewGroup? = null
val view = container?.inflate(R.layout.my)
But ViewGroup does not have
inflate...
fun ViewGroup.inflate(layoutId: Int): View {
return LayoutInflater.from(context).inflate(id, this, false)
}
...it does now
Just add following into any Kotlin file:
infix fun Int.benGurion(x: Int): Int {
return (this + x) * 1_000
}
a = 3 benGurion 17 // equals to 20 000
...we defined an operator, just like C++
Infix notation
fun ViewGroup.inflate(id: Int, attach: Boolean = false): View {
return LayoutInflater.from(context).inflate(id, this, attach)
}
container?.inflate(R.layout.fragment_my) // default: false
container?.inflate(R.layout.fragment_my, true)
...just like C++
Default values in parameters
typealias Credentials = Pair<String, String>
var shaul = Credentials("shaul", "p455w0rd")
...just like C++ typedef
Type aliases
apply plugin: 'kotlin-android-extensions'
Android extensions
// old code:
textView = view?.findViewById(R.id.text_view) as TextView?
textView ?.setEnabled(true)
textView ?.text = "Shaul gaon"
// new code:
text_view?.setEnabled(true)
text_view?.text = "Shaul gaon"
Loads all parts of layout implicitly:
Lazy properties:
way to create non-nullable properties that are executed when used for first time
private val myTextView: TextView by lazy {
view?.findViewById(R.id.text) as TextView
}
myTextView.setText("Shaul gaon");// <-- Lazy executed!
Shorter form: type can be inferred from context, also remove property type
private val myTextView by lazy {
text_view
}
Higher order functions:
A higher-order function is a function that takes functions as
parameters, or returns a function.
Example:
fun logExecution(func: () -> Unit) {
Log.d("tag", "before executing func")
func()
Log.d("tag", "after executing func")
}
logExecution( { Log.d("tag", "I'm a function") } )
Added tag parameter:
fun logExecution(tag: String, func: () -> Unit) {
Log.d(tag, "before executing func")
func()
Log.d(tag, "after executing func")
}
logExecution("tag") { Log.d("tag", "I'm a function") }
Another example:
fun runAsync(func: () -> Unit) {
Thread(Runnable { func() }).start()
}
runAsync {
// i.e.: save something in the Database
}
Inlining lambdas:
Lambdas have a performance penalty, as they are anonymous classes that are
created when called, and GC-ed after. Inlining replaces calling code with lambda
code thus skipping new/GC cycle
inline fun runAsync(func: () -> Unit) {
Thread(Runnable { func() }).start()
}
runAsync {
// now we are running inline, no anon class was created
}
Collections
List, Set, Map:
val mutableList = mutableListOf(1, 2, 3)
val readOnlyList = listOf(1, 2, 3)
val mutableMap = mutableMapOf("1" to 1, "2" to 2)
val readOnlyMap = mapOf("1" to 1, "2" to 2)
val mutableSet = mutableSetOf(1, 2, 3, 3) // size is 3
val readOnlySet = setOf(1 ,2, 3, 3)
Collection operations:
val items = (1..100).toList()
val stringList = items
.filter { it % 2 == 0 }
.map{ it -> "$it"}
.take(25)
.asReversed()
Classes
Kotlin class overview
//primary constructor does not contain code, just inits the field
class MyClass(someData: String) {
init {
Log.d("MyClass", "initializer block is 2nd stage constructor")
Log.d("MyClass", "class created with $someData")
}
//secondary constructor can contain code
constructor(someData: String, parent: MyClass) : this(someData) {
if(hashCode() != parent.hashCode()) {
Log.d("MyClass", "we are not the same")
}
}
}
var first = MyClass("shaul") //calls primary constructor
var second = MyClass("shaul", MyClass("shimon"))//calls secondary constructor
Data classes
data class News(val title: String, val content: String)
var news = News("Title", "Once upon a time")
var news1 = News("Title1", "Long long time ago")
var hash = news.hashCode();
var newsTitle = news.title
var toString = news.toString()
if(news.equals(news1)) Log.d("TAG", "equal")
data class Complex(var real: Double, var img: Double)
operator fun Complex.plus(other: Complex): Complex {
val real = this.real + other.real
val img = this.img + other.img
return Complex(real, img)
}
var complex : Complex = Complex(1.1, 2.2) + Complex(3.3, 4.4)
Log.d("Tag", "complex is " + complex.toString())
//outputs: int is Complex(real=4.4, img=6.6)
...we overloaded an operator, just like C++
Operator overloading
object MySingleton {
fun myMethod() {
//do something
}
}
MySingleton.myMethod()
Singleton:
class Outer {
private val bar: Int = 1
class Nested {
fun foo() = 2
}
} // can't access members of outer
Nested classes:
class Outer {
private val bar: Int = 1
inner class Inner {
fun foo() = bar
}
} // can access members of outer
Inner classes:
textView.setOnEditorActionListener(object : TextView.OnEditorActionListener {
override fun onEditorAction(v: TextView?,
actionId: Int,
event: KeyEvent?): Boolean {
//do something
}
})
Anonymous inner classes:
Connecting the dots
Java example:
db.beginTransaction();
try{
db.delete("table", "name = ?", new String[] {"shaul"});
} finally {
db.endTransaction();
}
We had a bug:
db.beginTransaction();
try{
db.delete("table", "name = ?", new String[] {"shaul"});
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Solution:
fun SQLiteDatabase.inTransaction(func: () -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
db.inTransaction {
db.delete("table", "name = ?", arrayOf("shaul"))
}
Better, pass the database:
fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit) {
beginTransaction()
try {
func(it)
setTransactionSuccessful()
} finally {
endTransaction()
}
}
db.inTransaction {
it.delete("table", "name = ?", arrayOf("shaul"))
}
Change it to be extension method of db:
fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
db.inTransaction {
delete("table", "name = ?", arrayOf("shaul"))
}
Inline it for performance:
inline fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
db.inTransaction {
delete("table", "name = ?", arrayOf("shaul"))
}
Further reading for more advanced topics:
● Generics: https://kotlinlang.org/docs/reference/generics.html
● Annotations: https://kotlinlang.org/docs/reference/annotations.html
● Reflection: https://kotlinlang.org/docs/reference/reflection.html
● Coroutines: https://kotlinlang.org/docs/reference/coroutines.html
The end?
"Now this is not the end. It is not even the
beginning of the end. But it is, perhaps, the
end of the beginning."
- Winston Churchill

More Related Content

What's hot

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
Speck&Tech
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
Kurt Renzo Acosta
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
Garth Gilmour
 
Introduction to Kotlin
Introduction to KotlinIntroduction to Kotlin
Introduction to Kotlin
T.M. Ishrak Hussain
 
Android Development with Kotlin course
Android Development  with Kotlin courseAndroid Development  with Kotlin course
Android Development with Kotlin course
GoogleDevelopersLeba
 
Kotlin Tutorial for Beginners | Kotlin Android Tutorial | Edureka
Kotlin Tutorial for Beginners | Kotlin Android Tutorial | EdurekaKotlin Tutorial for Beginners | Kotlin Android Tutorial | Edureka
Kotlin Tutorial for Beginners | Kotlin Android Tutorial | Edureka
Edureka!
 
Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021
Nelson Glauber Leal
 
Introduction to Android Develpment
Introduction to Android DevelpmentIntroduction to Android Develpment
Introduction to Android Develpment
NikhilPawar932560
 
Kotlin
KotlinKotlin
Kotlin
Rory Preddy
 
Kotlin Multiplatform
Kotlin MultiplatformKotlin Multiplatform
Kotlin Multiplatform
Kevin Galligan
 
Jetpack Compose.pptx
Jetpack Compose.pptxJetpack Compose.pptx
Jetpack Compose.pptx
GDSCVJTI
 
Kotlin vs Java | Edureka
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | Edureka
Edureka!
 
Android Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - IntroductionAndroid Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - Introduction
Andreas Jakl
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
Dariusz Lorenc
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
Ramon Ribeiro Rabello
 
Intro to kotlin
Intro to kotlinIntro to kotlin
Intro to kotlin
Tomislav Homan
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
Atif AbbAsi
 
Oop in kotlin
Oop in kotlinOop in kotlin
Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
Syed Awais Mazhar Bukhari
 
Kotlin Overview
Kotlin OverviewKotlin Overview
Kotlin Overview
Ekta Raj
 

What's hot (20)

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
Introduction to Kotlin
Introduction to KotlinIntroduction to Kotlin
Introduction to Kotlin
 
Android Development with Kotlin course
Android Development  with Kotlin courseAndroid Development  with Kotlin course
Android Development with Kotlin course
 
Kotlin Tutorial for Beginners | Kotlin Android Tutorial | Edureka
Kotlin Tutorial for Beginners | Kotlin Android Tutorial | EdurekaKotlin Tutorial for Beginners | Kotlin Android Tutorial | Edureka
Kotlin Tutorial for Beginners | Kotlin Android Tutorial | Edureka
 
Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021
 
Introduction to Android Develpment
Introduction to Android DevelpmentIntroduction to Android Develpment
Introduction to Android Develpment
 
Kotlin
KotlinKotlin
Kotlin
 
Kotlin Multiplatform
Kotlin MultiplatformKotlin Multiplatform
Kotlin Multiplatform
 
Jetpack Compose.pptx
Jetpack Compose.pptxJetpack Compose.pptx
Jetpack Compose.pptx
 
Kotlin vs Java | Edureka
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | Edureka
 
Android Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - IntroductionAndroid Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - Introduction
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
 
Intro to kotlin
Intro to kotlinIntro to kotlin
Intro to kotlin
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
 
Oop in kotlin
Oop in kotlinOop in kotlin
Oop in kotlin
 
Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
 
Kotlin Overview
Kotlin OverviewKotlin Overview
Kotlin Overview
 

Similar to Introduction to kotlin

K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
scalaconfjp
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
Arnaud Giuliani
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Сбертех | SberTech
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
Minseo Chayabanjonglerd
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
Fabio Collini
 
Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In Scala
Joey Gibson
 
Kotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonKotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparison
Ed Austin
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Codemotion
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
Mohamed Nabil, MSc.
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
Stephan Janssen
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»
e-Legion
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
Vasil Remeniuk
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
Christoph Pickl
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
Razvan Cojocaru
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Practical tips for building apps with kotlin
Practical tips for building apps with kotlinPractical tips for building apps with kotlin
Practical tips for building apps with kotlin
Adit Lal
 

Similar to Introduction to kotlin (20)

K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In Scala
 
Kotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonKotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparison
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Practical tips for building apps with kotlin
Practical tips for building apps with kotlinPractical tips for building apps with kotlin
Practical tips for building apps with kotlin
 

More from Shaul Rosenzwieg

Brainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a proBrainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a pro
Shaul Rosenzwieg
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
Shaul Rosenzwieg
 
Android Open Accessory
Android Open AccessoryAndroid Open Accessory
Android Open Accessory
Shaul Rosenzwieg
 
Lifecycle of a pixel
Lifecycle of a pixelLifecycle of a pixel
Lifecycle of a pixel
Shaul Rosenzwieg
 
Secure Android Development
Secure Android DevelopmentSecure Android Development
Secure Android Development
Shaul Rosenzwieg
 
Android virtual machine internals
Android virtual machine internalsAndroid virtual machine internals
Android virtual machine internals
Shaul Rosenzwieg
 
Binder: Android IPC
Binder: Android IPCBinder: Android IPC
Binder: Android IPC
Shaul Rosenzwieg
 
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
Shaul Rosenzwieg
 

More from Shaul Rosenzwieg (8)

Brainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a proBrainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a pro
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
 
Android Open Accessory
Android Open AccessoryAndroid Open Accessory
Android Open Accessory
 
Lifecycle of a pixel
Lifecycle of a pixelLifecycle of a pixel
Lifecycle of a pixel
 
Secure Android Development
Secure Android DevelopmentSecure Android Development
Secure Android Development
 
Android virtual machine internals
Android virtual machine internalsAndroid virtual machine internals
Android virtual machine internals
 
Binder: Android IPC
Binder: Android IPCBinder: Android IPC
Binder: Android IPC
 
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
 

Recently uploaded

Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 

Recently uploaded (20)

Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 

Introduction to kotlin

  • 1. Introduction to Kotlin Brief intro to the language
  • 2. What is Kotlin? “Kotlin is a Concise, Safe and Statically typed programming language focused on Interoperability with Java.” ● Compiles to JVM bytecode class files ● Generates Java 6, Java 8 or JS compatible bytecode, or LLVM binary ● Has good plugin for IntelliJ and Android Studio ● From Android Studio 3 (currently canary), fully supported out of the box ● A lot of features solve Java pitfalls
  • 4. The words “extends” and “implement” were replaced by a colon “:” class MainActivity : AppCompatActivity()
  • 5. Define functions inside our class with the “fun” keyword and the return type is added to the end. void is implicit override fun onCreate(savedState: Bundle?) :Int { } fun sum(a: Int, b: Int) = a + b
  • 6. Bye-bye semicolon: in Kotlin semicolon is optional val price = 100
  • 7. var is a variable. val is a constant val price = 100 // Int price = 30 // won't compile! it's a constant var total = price * 3 // Int val name = "Shaul haTotach" // String
  • 8. You can specify the type explicitly: val lastname : String = "Shaul haGadol" var size : Double = 30.0 var time : Float = 15f
  • 9. If you want to init a var later lateinit var notInited: TextView
  • 10. Equality a === b // reference equality a !== b a == b // content equality a != b
  • 11. Properties are treated like fields resources.getString(R.string.app_name) // still allowed: getResources().getString(R.string.app_name)
  • 12. Everything is non-nullable implicitly val a : String = null // won't compile! val ok : String? = null // OK :)
  • 13. Safe call val context : Context? = null // not crash, res will be null: val res = context?.getResources()
  • 14. Non null assertion operator val context : Context? = null // Will throw NPE: val res = context!!.getResources()
  • 15. Smart cast, why? //bad way to do it: val context : Context? = null val res = context?.getResources() val appName = res?.getString(R.string.app_name) val shortName = appName?.substring(0, 2)
  • 16. Check if it is null and inside of the block it is considered non-nullable: val context : Context? = null if (context != null) { // Don't need '?' anymore val res = context.getResources() val appName = res.getString(R.string.app_name) val shortName = appName.substring(0, 2) }
  • 17. Elvis operator simplified try { // code... } catch (e: Throwable) { Log.e("TAG", e.message ?: "Error message") }
  • 18. Unsafe cast: throws if cast not possible val bar = findViewById(R.id.bar) as ActionBar
  • 19. Ranges: for (i in 1..4) Log.d(TAG, "got $i") // "1234" for (i in 4 downTo 1) Log.d(TAG, "got $i") // "4321" for (i in 1..4 step 2) print(i) // "13" if (i in 1..10) println(i) // 1 <= i && i <= 10
  • 20. When: when (x) { 1 -> Log.d("tag", "one") 2 -> Log.d("tag", "two") else -> { // Note the block Log.d("tag", "many") } }
  • 21. Advanced when: when (x) { parseInt(s) -> print("s encodes x") in 1..10 -> print("x is in the range") in validNumbers -> print("x is valid") !in 10..20 -> print("x is outside the range") else -> print("none of the above") }
  • 22. When with no clause: when { x.isOdd() -> print("x is odd") x.isEven() -> print("x is even") else -> print("x is funny") }
  • 24. Can extend functionality of a class without writing a new class val container : ViewGroup? = null val view = container?.inflate(R.layout.my) But ViewGroup does not have inflate...
  • 25. fun ViewGroup.inflate(layoutId: Int): View { return LayoutInflater.from(context).inflate(id, this, false) } ...it does now Just add following into any Kotlin file:
  • 26. infix fun Int.benGurion(x: Int): Int { return (this + x) * 1_000 } a = 3 benGurion 17 // equals to 20 000 ...we defined an operator, just like C++ Infix notation
  • 27. fun ViewGroup.inflate(id: Int, attach: Boolean = false): View { return LayoutInflater.from(context).inflate(id, this, attach) } container?.inflate(R.layout.fragment_my) // default: false container?.inflate(R.layout.fragment_my, true) ...just like C++ Default values in parameters
  • 28. typealias Credentials = Pair<String, String> var shaul = Credentials("shaul", "p455w0rd") ...just like C++ typedef Type aliases
  • 29. apply plugin: 'kotlin-android-extensions' Android extensions // old code: textView = view?.findViewById(R.id.text_view) as TextView? textView ?.setEnabled(true) textView ?.text = "Shaul gaon" // new code: text_view?.setEnabled(true) text_view?.text = "Shaul gaon" Loads all parts of layout implicitly:
  • 30. Lazy properties: way to create non-nullable properties that are executed when used for first time private val myTextView: TextView by lazy { view?.findViewById(R.id.text) as TextView } myTextView.setText("Shaul gaon");// <-- Lazy executed! Shorter form: type can be inferred from context, also remove property type private val myTextView by lazy { text_view }
  • 31. Higher order functions: A higher-order function is a function that takes functions as parameters, or returns a function.
  • 32. Example: fun logExecution(func: () -> Unit) { Log.d("tag", "before executing func") func() Log.d("tag", "after executing func") } logExecution( { Log.d("tag", "I'm a function") } )
  • 33. Added tag parameter: fun logExecution(tag: String, func: () -> Unit) { Log.d(tag, "before executing func") func() Log.d(tag, "after executing func") } logExecution("tag") { Log.d("tag", "I'm a function") }
  • 34. Another example: fun runAsync(func: () -> Unit) { Thread(Runnable { func() }).start() } runAsync { // i.e.: save something in the Database }
  • 35. Inlining lambdas: Lambdas have a performance penalty, as they are anonymous classes that are created when called, and GC-ed after. Inlining replaces calling code with lambda code thus skipping new/GC cycle inline fun runAsync(func: () -> Unit) { Thread(Runnable { func() }).start() } runAsync { // now we are running inline, no anon class was created }
  • 37. List, Set, Map: val mutableList = mutableListOf(1, 2, 3) val readOnlyList = listOf(1, 2, 3) val mutableMap = mutableMapOf("1" to 1, "2" to 2) val readOnlyMap = mapOf("1" to 1, "2" to 2) val mutableSet = mutableSetOf(1, 2, 3, 3) // size is 3 val readOnlySet = setOf(1 ,2, 3, 3)
  • 38. Collection operations: val items = (1..100).toList() val stringList = items .filter { it % 2 == 0 } .map{ it -> "$it"} .take(25) .asReversed()
  • 40. Kotlin class overview //primary constructor does not contain code, just inits the field class MyClass(someData: String) { init { Log.d("MyClass", "initializer block is 2nd stage constructor") Log.d("MyClass", "class created with $someData") } //secondary constructor can contain code constructor(someData: String, parent: MyClass) : this(someData) { if(hashCode() != parent.hashCode()) { Log.d("MyClass", "we are not the same") } } } var first = MyClass("shaul") //calls primary constructor var second = MyClass("shaul", MyClass("shimon"))//calls secondary constructor
  • 41. Data classes data class News(val title: String, val content: String) var news = News("Title", "Once upon a time") var news1 = News("Title1", "Long long time ago") var hash = news.hashCode(); var newsTitle = news.title var toString = news.toString() if(news.equals(news1)) Log.d("TAG", "equal")
  • 42. data class Complex(var real: Double, var img: Double) operator fun Complex.plus(other: Complex): Complex { val real = this.real + other.real val img = this.img + other.img return Complex(real, img) } var complex : Complex = Complex(1.1, 2.2) + Complex(3.3, 4.4) Log.d("Tag", "complex is " + complex.toString()) //outputs: int is Complex(real=4.4, img=6.6) ...we overloaded an operator, just like C++ Operator overloading
  • 43. object MySingleton { fun myMethod() { //do something } } MySingleton.myMethod() Singleton:
  • 44. class Outer { private val bar: Int = 1 class Nested { fun foo() = 2 } } // can't access members of outer Nested classes:
  • 45. class Outer { private val bar: Int = 1 inner class Inner { fun foo() = bar } } // can access members of outer Inner classes:
  • 46. textView.setOnEditorActionListener(object : TextView.OnEditorActionListener { override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean { //do something } }) Anonymous inner classes:
  • 48. Java example: db.beginTransaction(); try{ db.delete("table", "name = ?", new String[] {"shaul"}); } finally { db.endTransaction(); }
  • 49. We had a bug: db.beginTransaction(); try{ db.delete("table", "name = ?", new String[] {"shaul"}); db.setTransactionSuccessful(); } finally { db.endTransaction(); }
  • 50. Solution: fun SQLiteDatabase.inTransaction(func: () -> Unit) { beginTransaction() try { func() setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { db.delete("table", "name = ?", arrayOf("shaul")) }
  • 51. Better, pass the database: fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit) { beginTransaction() try { func(it) setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { it.delete("table", "name = ?", arrayOf("shaul")) }
  • 52. Change it to be extension method of db: fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) { beginTransaction() try { func() setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { delete("table", "name = ?", arrayOf("shaul")) }
  • 53. Inline it for performance: inline fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) { beginTransaction() try { func() setTransactionSuccessful() } finally { endTransaction() } } db.inTransaction { delete("table", "name = ?", arrayOf("shaul")) }
  • 54. Further reading for more advanced topics: ● Generics: https://kotlinlang.org/docs/reference/generics.html ● Annotations: https://kotlinlang.org/docs/reference/annotations.html ● Reflection: https://kotlinlang.org/docs/reference/reflection.html ● Coroutines: https://kotlinlang.org/docs/reference/coroutines.html
  • 56. "Now this is not the end. It is not even the beginning of the end. But it is, perhaps, the end of the beginning." - Winston Churchill