SlideShare une entreprise Scribd logo
1  sur  45
Kotlin – The Future of Android
DJ RAUSCH
ANDROID ENGINEER @ MOKRIYA
Kotlin – The Future of Android
What is Kotlin?
◦ Kotlin is a statically typed JVM language developed by Jetbrains. Jetbrains also develops IntelliJ IDEA,
which Android Studio is based off of.
◦ Kotlin compiles to Java bytecode, so it runs everywhere Java does.
◦ Kotlin has first class Java interoperability
◦ Use Java classes in Kotlin
◦ Use Kotlin classes in Java
Comparison
JAVA KOTLIN
Variable Comparison
JAVA KOTLIN
val type: Int
val color = 1
var size: Int
var foo = 20
final int type;
final int color = 1;
int size = 0;
int foo = 20;
Null Comparison
JAVA KOTLIN
String person = null;
if (person != null) {
int length = person.length();
}
var person: String? = null
var personNonNull: String = ""
var length = person?.length
var lengthNonNull = personNonNull.length
Strings
JAVA
String firstName = "DJ";
String lastName = "Rausch";
String welcome = "Hi " + firstName
+ " " + lastName;
String nameLength = "You name is “
+ (firstName.length() +
lastName.length())
+ " letters";
KOTLIN
val firstName = "DJ"
val lastName = "Rausch"
val welcome = "Hello $firstName
$lastName"
val nameLength = "Your name is
${firstName.length +
lastName.length}
letters"
Switch
JAVA KOTLIN
String gradeLetter = "";
int grade = 92;
switch (grade) {
case 0:
gradeLetter = "F";
break;
//...
case 90:
gradeLetter = "A";
break;
}
var grade = 92
var gradeLetter = when(grade){
in 0..59->"f"
in 60..69->"d"
in 70..79->"c"
in 80..89->"b"
in 90..100->"a"
else -> "N/A"
}
Loops
JAVA KOTLIN
for(int i = 0; i<10; i++){}
for(int i = 0; i<10; i+=2){}
for(String name:names){}
for (i in 0..9) {}
for (i in 0..9 step 2){}
for(name in names){}
Collections
JAVA KOTLIN
List<Integer> numbers
= Arrays.asList(1, 2, 3);
final Map<Integer, String> map
= new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
val numbers = listOf(1, 2, 3)
var map = mapOf(
1 to "One",
2 to "Two",
3 to "Three")
Collections Continued
JAVA KOTLIN
for (int number : numbers) {
System.out.println(number);
}
for (int number : numbers) {
if (number > 5) {
System.out.println(number);
}
}
numbers.forEach {
println(it)
}
numbers.filter { it > 5 }
.forEach { println(it) }
Enums
JAVA KOTLIN
public enum Size {
XS(1),S(2),M(3),L(4),XL(5);
private int sizeNumber;
private Size(int sizeNumber) {
this.sizeNumber =
sizeNumber;
}
public int getSizeNumber() {
return sizeNumber;
}
}
enum class Size(val sizeNumber: Int){
XS(1),S(2),M(3),L(4),XL(5)
}
Casting and Type Checking
JAVA KOTLIN
Object obj = "";
if(obj instanceof String){}
if(!(obj instanceof String)){}
String s = (String) obj;
val obj = ""
if (obj is String) { }
if (obj !is String) { }
val s = obj as String
val s1 = obj
Kotlin Features
Data Class
data class Color(val name:String, val hex: String)
val c = Color("Blue","#000088")
val hexColor = c.hex
Elvis Operator
var name: String? = null
val length = name?.length ?: 0
Extensions
fun Int.asMoney(): String {
return "$$this"
}
val money = 100.asMoney()
Infix Functions
infix fun Int.times(x: Int): Int {
return this * x;
}
val result = 2 times 3
Destructing Declarations
val c = Color("Blue", "#000088")
val (name, hex) = c
println(name) //Prints Blue
println(hex) //Prints #000088
Lazy
val name: String by lazy {
"DJ Rausch"
}
Coroutines
val deferred = (1..1000000).map { n ->
async(CommonPool) {
delay(1000)
n
}
}
runBlocking {
val sum = deferred.sumBy { it.await() }
println(sum)
}
https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
Android Extensions
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_kotlin.*
class KotlinActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin)
kt_hello_text_view.text = "Hello World!"
}
}
Android Extensions Continued
((TextView)this._$_findCachedViewById(id.kt_hello_text_view)).setText((CharSequence)"Hello World!");
public View _$_findCachedViewById(int var1) {
if(this._$_findViewCache == null) {
this._$_findViewCache = new HashMap();
}
View var2 = (View)this._$_findViewCache.get(Integer.valueOf(var1));
if(var2 == null) {
var2 = this.findViewById(var1);
this._$_findViewCache.put(Integer.valueOf(var1), var2);
}
return var2;
}
Anko
Anko is a Kotlin library which makes Android application development faster and easier. It makes
your code clean and easy to read, and lets you forget about rough edges of the Android SDK for
Java.
Anko consists of several parts:
Anko Commons: a lightweight library full of helpers for intents, dialogs, logging and so on;
Anko Layouts: a fast and type-safe way to write dynamic Android layouts;
Anko SQLite: a query DSL and parser collection for Android SQLite;
Anko Coroutines: utilities based on the kotlinx.coroutines library.
Anko - Intents
startActivity<MainActivity>()
startActivity<MainActivity>("id" to 1)
Anko – Toasts
toast("Hello ${name.text}")
toast(R.string.app_name)
longToast("LOOOONNNNGGGGG")
Anko – Dialogs
alert("Hello ${name.text}","Are you awesome?"){
yesButton {
toast("Well duh")
}
noButton {
toast("Well at least DJ is awesome!")
}
}
Anko – Progress Dialog
val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")
indeterminateProgressDialog(message = "Loading something...", title = "LOADING")
Anko – Selector
val teams = listOf("University of Arizona", "Oregon", "ASU", "UCLA")
selector("Who won the Pac 12 Basketball Tournament in 2017?", teams, { _, i ->
//Do something
})
Anko – Layouts
class AnkoActivityUI : AnkoComponent<AnkoActivity> {
override fun createView(ui: AnkoContext<AnkoActivity>) = ui.apply {
verticalLayout {
padding = dip(20)
val name = editText()
button("Say Hello (Toast)") {
onClick {
toast("Hello ${name.text}")
}
}
}
}
}
Anko – Layouts Continued
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AnkoActivityUI().setContentView(this)
}
Anko – Sqlite
fun getUsers(db: ManagedSQLiteOpenHelper): List<User> = db.use {
db.select("Users")
.whereSimple("family_name = ?", "Rausch")
.doExec()
.parseList(UserParser)
}
Java Kotlin Interoperability
For the most part, it just works!
Java in Kotlin
public class JavaObject {
private String name;
private String otherName;
public JavaObject(String name, String otherName) {
this.name = name;
this.otherName = otherName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOtherName() {
return otherName;
}
public void setOtherName(String otherName) {
this.otherName = otherName;
}
}
Java in Kotlin Continued
val javaObject = JavaObject("Hello", "World")
println(javaObject.name)
println(javaObject.otherName)
Kotlin in Java
data class KotlinObject(var name: String, var otherName: String)
Kotlin in Java Continued
KotlinObject kotlinObject = new KotlinObject("Hello", "World");
System.out.println(kotlinObject.getName());
System.out.println(kotlinObject.getOtherName());
Moving to Kotlin
•Very simple moving to Kotlin
•Android Studio can convert files for you
• You may need to fix a few errors it creates.
Viewing Java Byte Code
Kotlin EVERYWHERE
•Android
•Server
•Javascript
•Native
Kotlin Server (Ktor)
fun main(args: Array<String>) {
embeddedServer(Netty, 8080) {
routing {
get("/") {
call.respondText("Hello, World!", ContentType.Text.Html)
}
}
}.start(wait = true)
}
Kotlin Javascript
fun main(args: Array<String>) {
val message = "Hello JavaScript!"
println(message)
}
Kotlin Javascript Continued
if (typeof kotlin === 'undefined') {
throw new Error("Error loading module 'JSExample_main'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'JSExample_main'.");
}
var JSExample_main = function (_, Kotlin) {
'use strict';
var println = Kotlin.kotlin.io.println_s8jyv4$;
function main(args) {
var message = 'Hello JavaScript!';
println(message);
}
_.main_kand9s$ = main;
main([]);
Kotlin.defineModule('JSExample_main', _);
return _;
}(typeof JSExample_main === 'undefined' ? {} : JSExample_main, kotlin);
Kotlin Native
•Will eventually allow for Kotlin to run practically anywhere.
• iOS, embedded platforms, etc
•Still early days
• https://github.com/JetBrains/kotlin-native
Questions?
Slides will be on my website soon™
https://djraus.ch
djrausch
Kotlin – The Future of Android Development

Contenu connexe

Tendances

Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
Java → kotlin: Tests Made Simple
Java → kotlin: Tests Made SimpleJava → kotlin: Tests Made Simple
Java → kotlin: Tests Made Simpleleonsabr
 
Kotlin: a better Java
Kotlin: a better JavaKotlin: a better Java
Kotlin: a better JavaNils Breunese
 
Excuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in KotlinExcuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in Kotlinleonsabr
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)intelliyole
 
Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspectiveNorman Richards
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
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
 
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
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and SimpleBen Mabey
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?intelliyole
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performanceintelliyole
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 

Tendances (20)

Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Java → kotlin: Tests Made Simple
Java → kotlin: Tests Made SimpleJava → kotlin: Tests Made Simple
Java → kotlin: Tests Made Simple
 
Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
 
Kotlin: a better Java
Kotlin: a better JavaKotlin: a better Java
Kotlin: a better Java
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 
Excuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in KotlinExcuse me, sir, do you have a moment to talk about tests in Kotlin
Excuse me, sir, do you have a moment to talk about tests in Kotlin
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
 
Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspective
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
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
 
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
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and Simple
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 

Similaire à Kotlin – The Future of Android Development

Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 
Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Davide Cerbo
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
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
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy DevelopmentMd Sazzad Islam
 
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 - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Mohamed Nabil, MSc.
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 

Similaire à Kotlin – The Future of Android Development (20)

Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
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
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Java
JavaJava
Java
 
Kickstart Kotlin
Kickstart KotlinKickstart Kotlin
Kickstart Kotlin
 
Beyond java8
Beyond java8Beyond java8
Beyond java8
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Kotlin : Happy Development
Kotlin : Happy DevelopmentKotlin : Happy Development
Kotlin : Happy Development
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
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 for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 

Dernier

An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 

Dernier (20)

An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 

Kotlin – The Future of Android Development

  • 1. Kotlin – The Future of Android DJ RAUSCH ANDROID ENGINEER @ MOKRIYA
  • 2. Kotlin – The Future of Android What is Kotlin? ◦ Kotlin is a statically typed JVM language developed by Jetbrains. Jetbrains also develops IntelliJ IDEA, which Android Studio is based off of. ◦ Kotlin compiles to Java bytecode, so it runs everywhere Java does. ◦ Kotlin has first class Java interoperability ◦ Use Java classes in Kotlin ◦ Use Kotlin classes in Java
  • 4. Variable Comparison JAVA KOTLIN val type: Int val color = 1 var size: Int var foo = 20 final int type; final int color = 1; int size = 0; int foo = 20;
  • 5. Null Comparison JAVA KOTLIN String person = null; if (person != null) { int length = person.length(); } var person: String? = null var personNonNull: String = "" var length = person?.length var lengthNonNull = personNonNull.length
  • 6. Strings JAVA String firstName = "DJ"; String lastName = "Rausch"; String welcome = "Hi " + firstName + " " + lastName; String nameLength = "You name is “ + (firstName.length() + lastName.length()) + " letters"; KOTLIN val firstName = "DJ" val lastName = "Rausch" val welcome = "Hello $firstName $lastName" val nameLength = "Your name is ${firstName.length + lastName.length} letters"
  • 7. Switch JAVA KOTLIN String gradeLetter = ""; int grade = 92; switch (grade) { case 0: gradeLetter = "F"; break; //... case 90: gradeLetter = "A"; break; } var grade = 92 var gradeLetter = when(grade){ in 0..59->"f" in 60..69->"d" in 70..79->"c" in 80..89->"b" in 90..100->"a" else -> "N/A" }
  • 8. Loops JAVA KOTLIN for(int i = 0; i<10; i++){} for(int i = 0; i<10; i+=2){} for(String name:names){} for (i in 0..9) {} for (i in 0..9 step 2){} for(name in names){}
  • 9. Collections JAVA KOTLIN List<Integer> numbers = Arrays.asList(1, 2, 3); final Map<Integer, String> map = new HashMap<>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); val numbers = listOf(1, 2, 3) var map = mapOf( 1 to "One", 2 to "Two", 3 to "Three")
  • 10. Collections Continued JAVA KOTLIN for (int number : numbers) { System.out.println(number); } for (int number : numbers) { if (number > 5) { System.out.println(number); } } numbers.forEach { println(it) } numbers.filter { it > 5 } .forEach { println(it) }
  • 11. Enums JAVA KOTLIN public enum Size { XS(1),S(2),M(3),L(4),XL(5); private int sizeNumber; private Size(int sizeNumber) { this.sizeNumber = sizeNumber; } public int getSizeNumber() { return sizeNumber; } } enum class Size(val sizeNumber: Int){ XS(1),S(2),M(3),L(4),XL(5) }
  • 12. Casting and Type Checking JAVA KOTLIN Object obj = ""; if(obj instanceof String){} if(!(obj instanceof String)){} String s = (String) obj; val obj = "" if (obj is String) { } if (obj !is String) { } val s = obj as String val s1 = obj
  • 14. Data Class data class Color(val name:String, val hex: String) val c = Color("Blue","#000088") val hexColor = c.hex
  • 15. Elvis Operator var name: String? = null val length = name?.length ?: 0
  • 16. Extensions fun Int.asMoney(): String { return "$$this" } val money = 100.asMoney()
  • 17. Infix Functions infix fun Int.times(x: Int): Int { return this * x; } val result = 2 times 3
  • 18. Destructing Declarations val c = Color("Blue", "#000088") val (name, hex) = c println(name) //Prints Blue println(hex) //Prints #000088
  • 19. Lazy val name: String by lazy { "DJ Rausch" }
  • 20. Coroutines val deferred = (1..1000000).map { n -> async(CommonPool) { delay(1000) n } } runBlocking { val sum = deferred.sumBy { it.await() } println(sum) } https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
  • 21. Android Extensions import android.os.Bundle import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_kotlin.* class KotlinActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_kotlin) kt_hello_text_view.text = "Hello World!" } }
  • 22. Android Extensions Continued ((TextView)this._$_findCachedViewById(id.kt_hello_text_view)).setText((CharSequence)"Hello World!"); public View _$_findCachedViewById(int var1) { if(this._$_findViewCache == null) { this._$_findViewCache = new HashMap(); } View var2 = (View)this._$_findViewCache.get(Integer.valueOf(var1)); if(var2 == null) { var2 = this.findViewById(var1); this._$_findViewCache.put(Integer.valueOf(var1), var2); } return var2; }
  • 23. Anko Anko is a Kotlin library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of the Android SDK for Java. Anko consists of several parts: Anko Commons: a lightweight library full of helpers for intents, dialogs, logging and so on; Anko Layouts: a fast and type-safe way to write dynamic Android layouts; Anko SQLite: a query DSL and parser collection for Android SQLite; Anko Coroutines: utilities based on the kotlinx.coroutines library.
  • 25. Anko – Toasts toast("Hello ${name.text}") toast(R.string.app_name) longToast("LOOOONNNNGGGGG")
  • 26. Anko – Dialogs alert("Hello ${name.text}","Are you awesome?"){ yesButton { toast("Well duh") } noButton { toast("Well at least DJ is awesome!") } }
  • 27. Anko – Progress Dialog val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data") indeterminateProgressDialog(message = "Loading something...", title = "LOADING")
  • 28. Anko – Selector val teams = listOf("University of Arizona", "Oregon", "ASU", "UCLA") selector("Who won the Pac 12 Basketball Tournament in 2017?", teams, { _, i -> //Do something })
  • 29. Anko – Layouts class AnkoActivityUI : AnkoComponent<AnkoActivity> { override fun createView(ui: AnkoContext<AnkoActivity>) = ui.apply { verticalLayout { padding = dip(20) val name = editText() button("Say Hello (Toast)") { onClick { toast("Hello ${name.text}") } } } } }
  • 30. Anko – Layouts Continued override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AnkoActivityUI().setContentView(this) }
  • 31. Anko – Sqlite fun getUsers(db: ManagedSQLiteOpenHelper): List<User> = db.use { db.select("Users") .whereSimple("family_name = ?", "Rausch") .doExec() .parseList(UserParser) }
  • 32. Java Kotlin Interoperability For the most part, it just works!
  • 33. Java in Kotlin public class JavaObject { private String name; private String otherName; public JavaObject(String name, String otherName) { this.name = name; this.otherName = otherName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOtherName() { return otherName; } public void setOtherName(String otherName) { this.otherName = otherName; } }
  • 34. Java in Kotlin Continued val javaObject = JavaObject("Hello", "World") println(javaObject.name) println(javaObject.otherName)
  • 35. Kotlin in Java data class KotlinObject(var name: String, var otherName: String)
  • 36. Kotlin in Java Continued KotlinObject kotlinObject = new KotlinObject("Hello", "World"); System.out.println(kotlinObject.getName()); System.out.println(kotlinObject.getOtherName());
  • 37. Moving to Kotlin •Very simple moving to Kotlin •Android Studio can convert files for you • You may need to fix a few errors it creates.
  • 40. Kotlin Server (Ktor) fun main(args: Array<String>) { embeddedServer(Netty, 8080) { routing { get("/") { call.respondText("Hello, World!", ContentType.Text.Html) } } }.start(wait = true) }
  • 41. Kotlin Javascript fun main(args: Array<String>) { val message = "Hello JavaScript!" println(message) }
  • 42. Kotlin Javascript Continued if (typeof kotlin === 'undefined') { throw new Error("Error loading module 'JSExample_main'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'JSExample_main'."); } var JSExample_main = function (_, Kotlin) { 'use strict'; var println = Kotlin.kotlin.io.println_s8jyv4$; function main(args) { var message = 'Hello JavaScript!'; println(message); } _.main_kand9s$ = main; main([]); Kotlin.defineModule('JSExample_main', _); return _; }(typeof JSExample_main === 'undefined' ? {} : JSExample_main, kotlin);
  • 43. Kotlin Native •Will eventually allow for Kotlin to run practically anywhere. • iOS, embedded platforms, etc •Still early days • https://github.com/JetBrains/kotlin-native
  • 44. Questions? Slides will be on my website soon™ https://djraus.ch djrausch

Notes de l'éditeur

  1. Java on the left, Kotlin on the right.
  2. val does not mean that it is immutable. In theory you could override the getter for the val and return whatever you want. But as a convention, if it is val, don’t override get. Types do not need to be declared. They will be inferred. Sometimes the compiler can not figure out what it is, and will ask for some help.
  3. Kotlin - ? Means var can be null. Setting a non nullable var to null is compile error. ?. = If not null !! = ignore null checks Person?.length would return null if person was null
  4. You can function calls, or just access fields in Kotlin, just like java with a cleaner syntax
  5. Pretty silly example, but it gets the point across. .. Checks the range
  6. Again, .. Checks the range, inclusive Step 2 is the same as +=
  7. it is the default name for the value. You can change it to whatever you want by defining it as name ->
  8. You get all the same functionality with kotlin as you do with java
  9. val s1 will be inferred as a string
  10. Now we will go over Kotlin specific features. These are designed to make life easier for you as a developer. Kotlin provides you a powerful toolset.
  11. Replaces POJOs with one line! Can declare additional functions if needed.
  12. Simplifies if else If(name != null){ length = name.length()} else{lenth = 0}
  13. Much like in Swift. We can add methods to anything. Lots of libraries have added support for this. Makes developing easier, and less random Util files. This may actually not work. There is an open issue about this in the kotlin bug tracker, but the basic idea is the same. I believe they are making it follow this syntax.
  14. They are member functions or extension functions; They have a single parameter; They are marked with the infix keyword.
  15. Maybe show decompiled version
  16. First call will load, subsequent calls return the cached result. Maybe show java code.
  17. So here we are going from 1 to 1000000 and adding all the ints. We have a delay to show how coroutines allow this to finish in a few seconds due to how many coroutines can one at once. Threads have more overhead that a coroutine, so the system cannot start as many threads.
  18. Need to use the extensions. Show code.
  19. This is what the kotlin code converts to in Java. We will talk about how to view this in a bit. Basics: Has a cache to store views. If there is no view, it will call findViewById. Obviously following calls will use the cached view reference.
  20. From https://github.com/Kotlin/anko You do need to wait for Anko to be updated when new support library views are added. Usually pretty quick
  21. You can pass intent extras in () From 4 lines to 1
  22. You can pass a string, or string resource
  23. I believe this is missing the show method.
  24. Progress dialogs are simplified with this. You can pass a custom Builder if you wanted. You can also use the dialog var much like you would normally. The same functions exist on it.
  25. This is like showing a list in a dialog and allowing one to be selected.
  26. Creating the layout in code. Create a class that extends AnkoComponent Supports support library views Actually faster than inflating xml - https://android.jlelse.eu/400-faster-layouts-with-anko-da17f32c45dd 400%
  27. I don’t have sample code for this, from the docs.
  28. Just show how to do this in Android Studio or IntelliJ
  29. Run this server and show it.
  30. Run and show it.