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

More Related Content

What's hot (20)

Hello Java 8
Hello Java 8Hello Java 8
Hello Java 8
Adam Davis
 
Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!
Christophe Alladoum
 
5 Minute Intro to Stetl
5 Minute Intro to Stetl5 Minute Intro to Stetl
5 Minute Intro to Stetl
Just van den Broecke
 
What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift Awesome
Sokna Ly
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
Vytautas Butkus
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) Microsoft
Jimmy 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++17
Daniel Eriksson
 
oojs
oojsoojs
oojs
Imran shaikh
 
Java 7
Java 7Java 7
Java 7
Bipul Sinha
 
Java object
Java objectJava object
Java object
shohan_slideshare
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
Misha Kozik
 
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 Time
Ted 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-android
lifecoder
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overview
Sergey Stupin
 
Learning groovy -EU workshop
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshop
adam1davis
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
dico_leque
 
Java8
Java8Java8
Java8
fbenault
 
Іван Лаврів "Transducers for ruby developers"
Іван Лаврів "Transducers for ruby developers"Іван Лаврів "Transducers for ruby developers"
Іван Лаврів "Transducers for ruby developers"
Forge Events
 
What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift Awesome
Sokna Ly
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
Vytautas Butkus
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) Microsoft
Jimmy 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++17
Daniel 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 Time
Ted 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-android
lifecoder
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overview
Sergey Stupin
 
Learning groovy -EU workshop
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshop
adam1davis
 
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
 

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

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
Speck&Tech
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
Clojure Small Intro
Clojure Small IntroClojure Small Intro
Clojure Small Intro
John Vlachoyiannis
 
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
Kamil 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 - 1
Mukesh Kumar
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
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 picaresque
Bret McGuire
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt Faluotico
WithTheBest
 
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
Luca Guadagnini
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
datamantra
 
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 2015
Jorg Janke
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
Stratio
 
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
Stoyan Nikolov
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
Chris 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 Developers
Miles 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 Developers
Skills 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 Developers
Jayaram Sankaranarayanan
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
Speck&Tech
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina 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 Javascript
Kamil 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 - 1
Mukesh Kumar
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
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 picaresque
Bret McGuire
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt Faluotico
WithTheBest
 
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
Luca Guadagnini
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
datamantra
 
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 2015
Jorg Janke
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
Stratio
 
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
Stoyan Nikolov
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
Chris 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 Developers
Miles 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 Developers
Skills 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 Developers
Jayaram Sankaranarayanan
 
Ad

Recently uploaded (20)

Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Ad

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