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

More Related Content

What's hot

Hello Java 8
Hello Java 8Hello Java 8
Hello Java 8
Adam Davis
 
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 AwesomeSokna 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) 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++17
Daniel Eriksson
 
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
 
Іван Лаврів "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 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 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 - 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 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 Checks
Stoyan 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 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 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 Developers
Jayaram 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

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 

Recently uploaded (20)

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 

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