SlideShare a Scribd company logo
1 of 18
Download to read offline
Kotlin workshop
Kotlin
● Statically typed, runs on JVM.
● Design goals
○ Concise - less code
○ Safe - avoid null pointer, class cast
○ Interoperable
○ Tool-friendly - any Java IDE, command line - or https://try.kotlinlang.org
● Mitigate weaknesses from Java
○ e.g. boilerplate and unsafe arrays
● Enforce best practices
○ Immutability, designing for inheritance, ...
● Open sourced by JetBrains since February 2012
A taste of code: Hello world
package se.svt.java;
public class Main {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
package se.svt.kotlin
fun main(args: Array<String>) {
println("Hello, world!")
}
● Top-level function
● fun keyword
● ‘;’
Variables and data types
● Focus on immutability
○ val vs var
● Type inference
○ val name = "deadline horse"
● Same basic data types as Java
○ Byte, Short, Int, Long, Float, Double
○ Char, String
○ Boolean
● Variables cannot* be null - must be explicitly nullable
○ Prevents NullPointerException
○ var username: String = "deadline horse"
○ var username: String? = null
Classes and Interfaces
● Interface
○ interface Clickable {..}
○ java uses extends, implements, Kotlin just ‘:’
● Data classes
○ used as data container
○ data class Being(val name: String, val age: Int)
● Inheritance
○ final (default), open, and abstract
● Properties
○ lateinit var being: Being
○ lazy - Computed only on demand
■ val maybeNotNeeded by lazy {...}
A taste of code
package se.svt.java;
public class Being {
private String name;
private Integer age;
private Boolean human;
public Being(String name, Integer age,
Boolean human) {
this.name = name;
this.age = age;
this.human = human;
}
public Boolean canVote(){
return human && (age > 18);
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
...
package se.svt.kotlin
class Being(val name: String, val age: Int, val human: Boolean){
fun canVote() = human && (age > 18)
}
Kotlin Standard Library
● A set of commonly used functions and annotations
○ https://kotlinlang.org/api/latest/jvm/stdlib/index.html
○ small size (Android)
● Higher order functions for functional programming
● Streams and Collections interface on top of java
○ List, Arrays, Maps, Sets, HashMap, HashSet etc.
○ Focus on immutability (read-only)
■ Lists: listOf() vs mutableListOf()
Control flow - conditionals
● Kotlin has if and when
○ when is like Java's switch but on steroids
● Both are expressions
● if replaces ternary condition operator
○ val msg = if (hasAccess) hello() else login()
if (isActive) {
doStuff()
} else {
cleanup()
}
when (state) {
WAITING -> wait()
RUNNING -> run()
}
Control flow - loops
● The for-loop
○ For any Iterable
○ Not (init; condition; action) structure!
● The while and do-while loop
○ Same as in Java and others
for (x in -3..3) {
doStuff()
}
for ((i, x) in array.withIndex()) {
println("the element at $i is $x")
}
Functions
fun ViewGroup.inflate(layout: Int): View {
return LayoutInflater.from(context).inflate(layout, this, false)
...
myViewGroup.inflate(R.layout.foo)
● Shorthand syntax
○ fun area(radius: Double) = Math.PI * radius * radius
● Default parameter values
○ fun join(strings:List<String>, delimiter: String = ",
", prefix = "", postfix = "")
● Named parameters
○ fun join(strings, prefix = "> ") : String {
"$prefix ${words.joinToString(separator = " ")}"
}
● Add extension function to any class:
Null handling - call operator
● Safe call operator
○ Propagates null if receiver is null
○ Cannot cause NPE
○ nullable?.someMethod()
● Elvis operator
○ Operation for null case
○ nullable?.someMethod() ?: someOtherMethod()
● Unsafe call operator
○ You assure compiler you know variable cannot be null!
○ Nullable!!.someMethod()
Kotlin features for functional programming
● Higher-order functions
○ As parameter
○ As return type
● Lambda expressions
○ Anonymous function, useful if only
used in one place
● Inline functions
○ Removing the overhead of lambdas
○ inline fun ...
fun runAsync(func: () -> Unit) {
Thread(Runnable { func() }).start()
}
fun doStuff() {
runAsync {
//access db, network etc
}
...
}
Kotlin features for functional programming con’t
Higher order functions for
collections
● take(n)
○ returns the first n items
● filter
○ returns items that match
predicate
● map
○ returns transform to other list
● sorted
○ returns a sorted list
● ...
val users = listOf(
Being("johnnyboy", 17, true),
Being("deadline horse", 35, false),
Being("rick", 61, true),
Being("morty", 14, true)
)
// chaining higher-order functions
val humans = users.filter { it.human }
.take(2)
.map { it.username }
.sorted()
Kotlin features for functional programming con’t
● Scope functions - higher order extensions from stdlib
● let: nullables or scoping
○ nullable?.let { doOnlyIfNotNull() }
● with: many calls on one (non-nullable!) object
● apply: initialization or builder-style
○ var p = Person().apply { name = "Deadline Horse";
age = 8 }
● also: actions on the side or validation
○ doSomething().also{require(...)log(...)}
● run: limit the scope of multiple local variables
receiver (this), argument (it) and result
Kotlin build process
Kotlin vs Java:Source code organization. Directories and
packages
Multiple classes in the same file
Any directory structure
One class per file
Packet <--> directory
hands-on
Gotcha’s
Classes - sealed by default - explicit declare ‘open’
Autoconvertert from java. Need to check all those !!
Handling nulls from the JDK
The inner it - easy to get lost on nested lambdas

More Related Content

What's hot

What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift AwesomeSokna Ly
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizenVytautas Butkus
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) MicrosoftJimmy Schementi
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17Daniel Eriksson
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 
Code Generation with Groovy, Lombok, AutoValue and Immutables - Ted's Tool Time
Code Generation with Groovy, Lombok, AutoValue and Immutables - Ted's Tool TimeCode Generation with Groovy, Lombok, AutoValue and Immutables - Ted's Tool Time
Code Generation with Groovy, Lombok, AutoValue and Immutables - Ted's Tool TimeTed Vinke
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin XPeppers
 
Scala on-android
Scala on-androidScala on-android
Scala on-androidlifecoder
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overviewSergey Stupin
 
Learning groovy -EU workshop
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshopadam1davis
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議dico_leque
 
Іван Лаврів "Transducers for ruby developers"
Іван Лаврів "Transducers for ruby developers"Іван Лаврів "Transducers for ruby developers"
Іван Лаврів "Transducers for ruby developers"Forge Events
 

What's hot (20)

Hello Java 8
Hello Java 8Hello Java 8
Hello Java 8
 
Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!
 
5 Minute Intro to Stetl
5 Minute Intro to Stetl5 Minute Intro to Stetl
5 Minute Intro to Stetl
 
What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift Awesome
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) Microsoft
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
 
oojs
oojsoojs
oojs
 
Java 7
Java 7Java 7
Java 7
 
Java object
Java objectJava object
Java object
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Code Generation with Groovy, Lombok, AutoValue and Immutables - Ted's Tool Time
Code Generation with Groovy, Lombok, AutoValue and Immutables - Ted's Tool TimeCode Generation with Groovy, Lombok, AutoValue and Immutables - Ted's Tool Time
Code Generation with Groovy, Lombok, AutoValue and Immutables - Ted's Tool Time
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Scala on-android
Scala on-androidScala on-android
Scala on-android
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overview
 
Learning groovy -EU workshop
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshop
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
 
Java8
Java8Java8
Java8
 
Іван Лаврів "Transducers for ruby developers"
Іван Лаврів "Transducers for ruby developers"Іван Лаврів "Transducers for ruby developers"
Іван Лаврів "Transducers for ruby developers"
 

Similar to Kotlin workshop 2018-06-11

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android DevelopmentSpeck&Tech
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptKamil Toman
 
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)PROIDEA
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)Andrés Viedma Peláez
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresqueBret McGuire
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt FaluoticoWithTheBest
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in KotlinLuca Guadagnini
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scaladatamantra
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
 
Dart the better Javascript 2015
Dart the better Javascript 2015Dart the better Javascript 2015
Dart the better Javascript 2015Jorg Janke
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scalaStratio
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksStoyan Nikolov
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2Chris Farrell
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersMiles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersJayaram Sankaranarayanan
 

Similar to Kotlin workshop 2018-06-11 (20)

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Clojure Small Intro
Clojure Small IntroClojure Small Intro
Clojure Small Intro
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
 
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresque
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt Faluotico
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Dart the better Javascript 2015
Dart the better Javascript 2015Dart the better Javascript 2015
Dart the better Javascript 2015
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time Checks
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 Developers
 

Recently uploaded

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 

Recently uploaded (20)

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 

Kotlin workshop 2018-06-11

  • 2. Kotlin ● Statically typed, runs on JVM. ● Design goals ○ Concise - less code ○ Safe - avoid null pointer, class cast ○ Interoperable ○ Tool-friendly - any Java IDE, command line - or https://try.kotlinlang.org ● Mitigate weaknesses from Java ○ e.g. boilerplate and unsafe arrays ● Enforce best practices ○ Immutability, designing for inheritance, ... ● Open sourced by JetBrains since February 2012
  • 3. A taste of code: Hello world package se.svt.java; public class Main { public static void main(String[] args) { System.out.println("Hello, world!"); } } package se.svt.kotlin fun main(args: Array<String>) { println("Hello, world!") } ● Top-level function ● fun keyword ● ‘;’
  • 4. Variables and data types ● Focus on immutability ○ val vs var ● Type inference ○ val name = "deadline horse" ● Same basic data types as Java ○ Byte, Short, Int, Long, Float, Double ○ Char, String ○ Boolean ● Variables cannot* be null - must be explicitly nullable ○ Prevents NullPointerException ○ var username: String = "deadline horse" ○ var username: String? = null
  • 5. Classes and Interfaces ● Interface ○ interface Clickable {..} ○ java uses extends, implements, Kotlin just ‘:’ ● Data classes ○ used as data container ○ data class Being(val name: String, val age: Int) ● Inheritance ○ final (default), open, and abstract ● Properties ○ lateinit var being: Being ○ lazy - Computed only on demand ■ val maybeNotNeeded by lazy {...}
  • 6. A taste of code package se.svt.java; public class Being { private String name; private Integer age; private Boolean human; public Being(String name, Integer age, Boolean human) { this.name = name; this.age = age; this.human = human; } public Boolean canVote(){ return human && (age > 18); } public String getName() { return name; } public Integer getAge() { return age; } ... package se.svt.kotlin class Being(val name: String, val age: Int, val human: Boolean){ fun canVote() = human && (age > 18) }
  • 7. Kotlin Standard Library ● A set of commonly used functions and annotations ○ https://kotlinlang.org/api/latest/jvm/stdlib/index.html ○ small size (Android) ● Higher order functions for functional programming ● Streams and Collections interface on top of java ○ List, Arrays, Maps, Sets, HashMap, HashSet etc. ○ Focus on immutability (read-only) ■ Lists: listOf() vs mutableListOf()
  • 8. Control flow - conditionals ● Kotlin has if and when ○ when is like Java's switch but on steroids ● Both are expressions ● if replaces ternary condition operator ○ val msg = if (hasAccess) hello() else login() if (isActive) { doStuff() } else { cleanup() } when (state) { WAITING -> wait() RUNNING -> run() }
  • 9. Control flow - loops ● The for-loop ○ For any Iterable ○ Not (init; condition; action) structure! ● The while and do-while loop ○ Same as in Java and others for (x in -3..3) { doStuff() } for ((i, x) in array.withIndex()) { println("the element at $i is $x") }
  • 10. Functions fun ViewGroup.inflate(layout: Int): View { return LayoutInflater.from(context).inflate(layout, this, false) ... myViewGroup.inflate(R.layout.foo) ● Shorthand syntax ○ fun area(radius: Double) = Math.PI * radius * radius ● Default parameter values ○ fun join(strings:List<String>, delimiter: String = ", ", prefix = "", postfix = "") ● Named parameters ○ fun join(strings, prefix = "> ") : String { "$prefix ${words.joinToString(separator = " ")}" } ● Add extension function to any class:
  • 11. Null handling - call operator ● Safe call operator ○ Propagates null if receiver is null ○ Cannot cause NPE ○ nullable?.someMethod() ● Elvis operator ○ Operation for null case ○ nullable?.someMethod() ?: someOtherMethod() ● Unsafe call operator ○ You assure compiler you know variable cannot be null! ○ Nullable!!.someMethod()
  • 12. Kotlin features for functional programming ● Higher-order functions ○ As parameter ○ As return type ● Lambda expressions ○ Anonymous function, useful if only used in one place ● Inline functions ○ Removing the overhead of lambdas ○ inline fun ... fun runAsync(func: () -> Unit) { Thread(Runnable { func() }).start() } fun doStuff() { runAsync { //access db, network etc } ... }
  • 13. Kotlin features for functional programming con’t Higher order functions for collections ● take(n) ○ returns the first n items ● filter ○ returns items that match predicate ● map ○ returns transform to other list ● sorted ○ returns a sorted list ● ... val users = listOf( Being("johnnyboy", 17, true), Being("deadline horse", 35, false), Being("rick", 61, true), Being("morty", 14, true) ) // chaining higher-order functions val humans = users.filter { it.human } .take(2) .map { it.username } .sorted()
  • 14. Kotlin features for functional programming con’t ● Scope functions - higher order extensions from stdlib ● let: nullables or scoping ○ nullable?.let { doOnlyIfNotNull() } ● with: many calls on one (non-nullable!) object ● apply: initialization or builder-style ○ var p = Person().apply { name = "Deadline Horse"; age = 8 } ● also: actions on the side or validation ○ doSomething().also{require(...)log(...)} ● run: limit the scope of multiple local variables receiver (this), argument (it) and result
  • 16. Kotlin vs Java:Source code organization. Directories and packages Multiple classes in the same file Any directory structure One class per file Packet <--> directory
  • 18. Gotcha’s Classes - sealed by default - explicit declare ‘open’ Autoconvertert from java. Need to check all those !! Handling nulls from the JDK The inner it - easy to get lost on nested lambdas