SlideShare a Scribd company logo
1 of 49
Download to read offline
KotlinDrew Stephens
<drew@dinomite.net>
@dinomite
Forum For All
1
What do I know?
— JVM (Java1.4–8
, KotlinM14–1.1
, Groovy1.5
)
— Ruby1.9–2.4
& Rails3.0–5.0
— Perl5.5–5.12
— PHP5.2–5.3
— JavaScript1.5–ECMAScript 6/ES2016/ES6 Harmony/WTF
(when I have to)
— Android & iOS in a pinch
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 2
What is it?
— A language for the JVM
— As easy to integrate as Groovy
— Syntax like Java, but cleaner
— Written by JetBrains, who wrote your IDE1
1
If you use the correct IDE
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 3
———————————
———————————
Statics———————————
———————————Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 4
Hate Java
Don't hate types
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 5
Static Dynamic
Java Ruby
C# Python
ObjectiveC JavaScript
Swift Perl
Kotlin PHP
Groovy Groovy !
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 6
Statics, generally
int foo = 7;
foo = "bar"; // compile error
if (foo == "bar") { // compile error
...
}
if (fooo == 7) { // compile error
...
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 7
Statics, generally
int foo = 7;
foo = "bar"; // compile error
if (foo == "bar") { // compile error
...
}
if (fooo == 7) { // compile error
...
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 8
Statics, generally
int foo = 7;
foo = "bar"; // compile error
if (foo == "bar") { // compile error
...
}
if (fooo == 7) { // compile error
...
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 9
Statics, generally
int foo = 7;
foo = "bar"; // compile error
if (foo == "bar") { // compile error
...
}
if (fooo == 7) { // compile error
...
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 10
Statics, generally
— Prevents misspelled variables
— Catch NoMethodError, NameError, undefined early
— Add context to the code
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 11
Equality
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 12
Productivity
— Unit tests can cover functionality, not borders
— Easy refactoring, thanks to powerful tools
— Hard to break things accidentally
— Much less reading the source APIs you're using
— No tracking down parameters
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 13
Updating a user's address
POST /address
{
"user_id": 44,
"address": {
"number": 2446,
"street": "Belmont Rd NW",
"zip": 20008
}
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 14
Param checking in Ruby
def update_address
check_params
...
end
def check_address_params
required_params = params.key?(:user_id) && params.key?(:address)
fail ActionController::ParameterMissing unless has_required_params
address = params[:address]
fail ActionController::ParameterMissing
unless address.key?(:number) && address.key?(:street) && address.key?(:zip)
# Doesn't verify types of anything
end
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 15
Param checking in Java
boolean updateAddress(AddressRequest newAddress) {
// Guaranteed to be well-formed
...
}
class AddressRequest {
int userId;
Address address;
}
class Address {
int number;
String street;
int zip;
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 16
———————————
———————————
Features———————————
———————————Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 17
Hello, world! (Java)
package demo;
public static void main(Array<String> args) {
try {
System.out.printf("Hello, world!");
} catch (IllegalFormatException e) {
e.printStackTrace();
}
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 18
Hello, World!
package demo
fun main(args: Array<String>) {
println("Hello, world!")
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 19
Variables
— vals are immutable (read-only; like final in Java)
— vars are mutable
— Type inference
val foo = "Foo" // is a String
foo = "Bar" // nope, can't change a val
var num = 7
num = 3 // ok
// Java
// final String foo = "Foo";
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 20
Null safety
var neverNull: String = "foobar"
var maybeNull: String? = "baz"
neverNull = null // Compiler error
neverNull.length // Guaranteed OK
maybeNull.length // Compiler error
maybeNull?.length // Possible null instead of length
maybeNull!!.length // Possible NPE
var valueOrSadness = maybeNull ?: "it was null !"
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 21
Null safety
var neverNull: String = "foobar"
var maybeNull: String? = "baz"
neverNull = null // Compiler error
neverNull.length // Guaranteed OK
maybeNull.length // Compiler error
maybeNull?.length // Possible null instead of length
maybeNull!!.length // Possible NPE
var valueOrSadness = maybeNull ?: "it was null !"
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 22
Null safety
var neverNull: String = "foobar"
var maybeNull: String? = "baz"
neverNull = null // Compiler error
neverNull.length // Guaranteed OK
maybeNull.length // Compiler error
maybeNull?.length // Possible null instead of length
maybeNull!!.length // Possible NPE
var valueOrSadness = maybeNull ?: "it was null !"
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 23
Null safety
var neverNull: String = "foobar"
var maybeNull: String? = "baz"
neverNull = null // Compiler error
neverNull.length // Guaranteed OK
maybeNull.length // Compiler error
maybeNull?.length // Possible null instead of length
maybeNull!!.length // Possible NPE
var valueOrSadness = maybeNull ?: "it was null !"
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 24
Null safety
var neverNull: String = "foobar"
var maybeNull: String? = "baz"
neverNull = null // Compiler error
neverNull.length // Guaranteed OK
maybeNull.length // Compiler error
maybeNull?.length // Possible null instead of length
maybeNull!!.length // Possible NPE
var valueOrSadness = maybeNull ?: "it was null !"
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 25
Null safety
var neverNull: String = "foobar"
var maybeNull: String? = "baz"
neverNull = null // Compiler error
neverNull.length // Guaranteed OK
maybeNull.length // Compiler error
maybeNull?.length // Possible null instead of length
maybeNull!!.length // Possible NPE
var valueOrSadness = maybeNull ?: "it was null !"
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 26
Null safety
var neverNull: String = "foobar"
var maybeNull: String? = "baz"
neverNull = null // Compiler error
neverNull.length // Guaranteed OK
maybeNull.length // Compiler error
maybeNull?.length // Possible null instead of length
maybeNull!!.length // Possible NPE
var valueOrSadness = maybeNull ?: "it was null !"
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 27
Null tracking
if (maybeNull != null && maybeNull.length > 5) {
// maybeNull guaranteed to not be
print("It is ${maybeNull.length} characters")
} else {
print("The variable is null !")
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 28
Type inference
fun returnsAListOfStrings(): List<String> {
return listOf("foo", "bar")
}
// Java
// final List<String> listOfStrings = returnsAListOfStrings();
// final String firstString = listOfStrings[0];
val listOfStrings = returnsAListOfStrings()
val firstString = listOfStrings[0]
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 29
Type inference
fun returnsAListOfStrings(): List<String> {
return listOf("foo", "bar")
}
// Java
// final List<String> listOfStrings = returnsAListOfStrings();
// final String firstString = listOfStrings[0];
val listOfStrings = returnsAListOfStrings()
val firstString = listOfStrings[0]
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 30
Type inference
fun returnsAListOfStrings(): List<String> {
return listOf("foo", "bar")
}
// Java
// final List<String> listOfStrings = returnsAListOfStrings();
// final String firstString = listOfStrings[0];
val listOfStrings = returnsAListOfStrings()
val firstString = listOfStrings[0]
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 31
POJO
public class Pagechat {
private final int id;
private final String url;
private final boolean fresh;
public Pagechat(int id, String url, boolean fresh) {
this.id = id;
this.url = url;
this.fresh = fresh;
}
public int getId() { return id; }
public String getUrl() { return url; }
public boolean getFresh() { return fresh; }
public boolean equals(Object obj) { … }
public int hashCode() { … }
public String toString() { … }
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 32
Data class (POJO equivalent)
data class Pagechat(val id: Int,
val url: String,
val fresh: Boolean)
Free stuff:
- Accessors for fields; setters for vars
- equals()/hashCode()
- toString()
- copy()
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 33
Param checking in Kotlin
fun updateAddress(newAddress: UpdateAddress): Boolean {
// Guaranteed to be well-formed
...
}
data class UpdateAddress(val userId: Int, val address: Address )
data class Address(val number: Int, val street: String, val zip: Int)
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 34
Using the copy constructor
data class Pagechat(val id: Int, val url: String, val fresh: Boolean)
...
fun createPagechat(url: String, fresh: Boolean): Pagechat {
val pagechat = Pagechat(0, "http://foobar.com", true)
// { id: 0, url: "http://foobar.com", fresh: true }
val newId = dao.insert(pagechat)
return pagechat.copy(id = newId)
// { id: $newId, url: "http://foobar.com", fresh: true }
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 35
Be!er switch statement (when)
when (view) {
is TextView -> toast(view.text)
is RecyclerView -> toast("Item count = ${view.adapter.itemCount}")
is SearchView -> toast("Current query: ${view.query}")
else -> toast("View type not supported")
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 36
Named arguments & defaults
data class User(name: String, email: String, admin: Boolean = false)
...
val drew = User("Drew", "drew@dinomite.net")
// drew.admin is false
val plague = User("The Plague", "babbage@ellingson.com", true)
// plague.admin is true
val named = User(email = "foo@bar.com", name = "Foo Bar")
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 37
Tail recursion4
tailrec fun findFixPoint(x: Double = 1.0): Double {
val cosine = Math.cos(x)
if (x == cosine) {
return x
} else {
return findFixPoint(cosine)
}
}
// Shorter
tailrec fun findFixPoint(x: Double = 1.0): Double
= if (x == Math.cos(x)) x else findFixPoint(Math.cos(x))
4
https://kotlinlang.org/docs/reference/functions.html#tail-recursive-functions
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 38
Be!er enums
enum class Matcher(val cssQuery: String,
val attr: String) {
OG_TITLE("meta[property=og:title]", "content"),
META_TITLE("meta[name=title]", "content"),
TITLE("title", null)
}
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 39
Be!er streams syntax
val cars = mapOf(
2 to "Vandoorne", 3 to "Ricciardo",
5 to "Vettel", 7 to "Räikkönen",
…
)
val qualified = listOf(44, 5, 77, 7, 33, …)
...
val grid = qualified.map { cars[it] }
// Java: qualified.stream().map(e -> cars.get(e))
// [Hamilton, Vettel, Bottas, Räikkönen, …]
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 40
———————————
———————————
How?———————————
———————————Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 41
How do I use it?
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 42
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.2"
}
}
apply plugin: 'kotlin'
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 43
Tell me more
- Kotlin docs—https://kotlinlang.org/docs/reference/
- Try Kotlin in your browser—http://try.kotlinlang.org/
- My Kotlin repos—https://github.com/dinomite
- Dynamic vs Static—https://youtu.be/Uxl_X3zXVAM
Drew Stephens
<drew@dinomite.net>
@dinomite
https://forumforall.net
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 44
———————————
———————————
———————————
———————————
———————————
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 45
JSON3
{
"id": 7,
"email": "drew@dinomite.net"
}
data class User(id: Int, email: String)
3
https://medium.com/square-corner-blog/kotlins-a-great-language-for-json-fcd6ef99256b
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 46
Simpler lambdas
takesLambdaArg(e -> e.getValue())
takesLambdaArg({ it.getValue() })
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 47
String interpolation
val foo = "foobar"
println("The variable is $foo")
// The variable is foobar
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 48
Embracing null2
fun findUser(id: Int): User?
...
findUser(7)?.let {
// Only executes if user exists
it.transmogrify(42)
}
2
http://beust.com/weblog/2016/01/14/a-close-look-at-kotlins-let/
Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 49

More Related Content

Similar to Kotlin Basics

Day 1 - Intro to Ruby
Day 1 - Intro to RubyDay 1 - Intro to Ruby
Day 1 - Intro to RubyBarry Jones
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new thingsDavid Black
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Wen-Tien Chang
 
2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekingeProf. Wim Van Criekinge
 
2015 bioinformatics python_strings_wim_vancriekinge
2015 bioinformatics python_strings_wim_vancriekinge2015 bioinformatics python_strings_wim_vancriekinge
2015 bioinformatics python_strings_wim_vancriekingeProf. Wim Van Criekinge
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformEastBanc Tachnologies
 
Happy Go Programming
Happy Go ProgrammingHappy Go Programming
Happy Go ProgrammingLin Yo-An
 
End-to-End Analysis of a Domain Generating Algorithm Malware Family
End-to-End Analysis of a Domain Generating Algorithm Malware FamilyEnd-to-End Analysis of a Domain Generating Algorithm Malware Family
End-to-End Analysis of a Domain Generating Algorithm Malware FamilyCrowdStrike
 
TypeScript와 Flow: 
자바스크립트 개발에 정적 타이핑 도입하기
TypeScript와 Flow: 
자바스크립트 개발에 정적 타이핑 도입하기TypeScript와 Flow: 
자바스크립트 개발에 정적 타이핑 도입하기
TypeScript와 Flow: 
자바스크립트 개발에 정적 타이핑 도입하기Heejong Ahn
 
Scala in practice - 3 years later
Scala in practice - 3 years laterScala in practice - 3 years later
Scala in practice - 3 years laterpatforna
 
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...Thoughtworks
 
Beauty & the Beast - Java VS TypeScript
Beauty & the Beast - Java VS TypeScriptBeauty & the Beast - Java VS TypeScript
Beauty & the Beast - Java VS TypeScriptHendrik Ebbers
 
CoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming courseCoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming courseAlexander Galkin
 
I don't know what I'm Doing: A newbie guide for Golang for DevOps
I don't know what I'm Doing: A newbie guide for Golang for DevOpsI don't know what I'm Doing: A newbie guide for Golang for DevOps
I don't know what I'm Doing: A newbie guide for Golang for DevOpsPeter Souter
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insAndrew Dupont
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in StyleBhavin Javia
 

Similar to Kotlin Basics (20)

Day 1 - Intro to Ruby
Day 1 - Intro to RubyDay 1 - Intro to Ruby
Day 1 - Intro to Ruby
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new things
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge2015 bioinformatics python_io_wim_vancriekinge
2015 bioinformatics python_io_wim_vancriekinge
 
2015 bioinformatics python_strings_wim_vancriekinge
2015 bioinformatics python_strings_wim_vancriekinge2015 bioinformatics python_strings_wim_vancriekinge
2015 bioinformatics python_strings_wim_vancriekinge
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Happy Go Programming
Happy Go ProgrammingHappy Go Programming
Happy Go Programming
 
End-to-End Analysis of a Domain Generating Algorithm Malware Family
End-to-End Analysis of a Domain Generating Algorithm Malware FamilyEnd-to-End Analysis of a Domain Generating Algorithm Malware Family
End-to-End Analysis of a Domain Generating Algorithm Malware Family
 
TypeScript와 Flow: 
자바스크립트 개발에 정적 타이핑 도입하기
TypeScript와 Flow: 
자바스크립트 개발에 정적 타이핑 도입하기TypeScript와 Flow: 
자바스크립트 개발에 정적 타이핑 도입하기
TypeScript와 Flow: 
자바스크립트 개발에 정적 타이핑 도입하기
 
Scala in practice - 3 years later
Scala in practice - 3 years laterScala in practice - 3 years later
Scala in practice - 3 years later
 
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
 
Beauty & the Beast - Java VS TypeScript
Beauty & the Beast - Java VS TypeScriptBeauty & the Beast - Java VS TypeScript
Beauty & the Beast - Java VS TypeScript
 
CoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming courseCoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming course
 
Intro
IntroIntro
Intro
 
I don't know what I'm Doing: A newbie guide for Golang for DevOps
I don't know what I'm Doing: A newbie guide for Golang for DevOpsI don't know what I'm Doing: A newbie guide for Golang for DevOps
I don't know what I'm Doing: A newbie guide for Golang for DevOps
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on android
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
 

Recently uploaded

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
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
 
(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
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
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
 
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
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
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
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
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
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
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
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
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
 
(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...
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
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
 
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
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
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
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
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
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
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
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 

Kotlin Basics

  • 2. What do I know? — JVM (Java1.4–8 , KotlinM14–1.1 , Groovy1.5 ) — Ruby1.9–2.4 & Rails3.0–5.0 — Perl5.5–5.12 — PHP5.2–5.3 — JavaScript1.5–ECMAScript 6/ES2016/ES6 Harmony/WTF (when I have to) — Android & iOS in a pinch Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 2
  • 3. What is it? — A language for the JVM — As easy to integrate as Groovy — Syntax like Java, but cleaner — Written by JetBrains, who wrote your IDE1 1 If you use the correct IDE Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 3
  • 5. Hate Java Don't hate types Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 5
  • 6. Static Dynamic Java Ruby C# Python ObjectiveC JavaScript Swift Perl Kotlin PHP Groovy Groovy ! Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 6
  • 7. Statics, generally int foo = 7; foo = "bar"; // compile error if (foo == "bar") { // compile error ... } if (fooo == 7) { // compile error ... } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 7
  • 8. Statics, generally int foo = 7; foo = "bar"; // compile error if (foo == "bar") { // compile error ... } if (fooo == 7) { // compile error ... } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 8
  • 9. Statics, generally int foo = 7; foo = "bar"; // compile error if (foo == "bar") { // compile error ... } if (fooo == 7) { // compile error ... } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 9
  • 10. Statics, generally int foo = 7; foo = "bar"; // compile error if (foo == "bar") { // compile error ... } if (fooo == 7) { // compile error ... } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 10
  • 11. Statics, generally — Prevents misspelled variables — Catch NoMethodError, NameError, undefined early — Add context to the code Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 11
  • 12. Equality Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 12
  • 13. Productivity — Unit tests can cover functionality, not borders — Easy refactoring, thanks to powerful tools — Hard to break things accidentally — Much less reading the source APIs you're using — No tracking down parameters Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 13
  • 14. Updating a user's address POST /address { "user_id": 44, "address": { "number": 2446, "street": "Belmont Rd NW", "zip": 20008 } } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 14
  • 15. Param checking in Ruby def update_address check_params ... end def check_address_params required_params = params.key?(:user_id) && params.key?(:address) fail ActionController::ParameterMissing unless has_required_params address = params[:address] fail ActionController::ParameterMissing unless address.key?(:number) && address.key?(:street) && address.key?(:zip) # Doesn't verify types of anything end Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 15
  • 16. Param checking in Java boolean updateAddress(AddressRequest newAddress) { // Guaranteed to be well-formed ... } class AddressRequest { int userId; Address address; } class Address { int number; String street; int zip; } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 16
  • 18. Hello, world! (Java) package demo; public static void main(Array<String> args) { try { System.out.printf("Hello, world!"); } catch (IllegalFormatException e) { e.printStackTrace(); } } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 18
  • 19. Hello, World! package demo fun main(args: Array<String>) { println("Hello, world!") } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 19
  • 20. Variables — vals are immutable (read-only; like final in Java) — vars are mutable — Type inference val foo = "Foo" // is a String foo = "Bar" // nope, can't change a val var num = 7 num = 3 // ok // Java // final String foo = "Foo"; Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 20
  • 21. Null safety var neverNull: String = "foobar" var maybeNull: String? = "baz" neverNull = null // Compiler error neverNull.length // Guaranteed OK maybeNull.length // Compiler error maybeNull?.length // Possible null instead of length maybeNull!!.length // Possible NPE var valueOrSadness = maybeNull ?: "it was null !" Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 21
  • 22. Null safety var neverNull: String = "foobar" var maybeNull: String? = "baz" neverNull = null // Compiler error neverNull.length // Guaranteed OK maybeNull.length // Compiler error maybeNull?.length // Possible null instead of length maybeNull!!.length // Possible NPE var valueOrSadness = maybeNull ?: "it was null !" Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 22
  • 23. Null safety var neverNull: String = "foobar" var maybeNull: String? = "baz" neverNull = null // Compiler error neverNull.length // Guaranteed OK maybeNull.length // Compiler error maybeNull?.length // Possible null instead of length maybeNull!!.length // Possible NPE var valueOrSadness = maybeNull ?: "it was null !" Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 23
  • 24. Null safety var neverNull: String = "foobar" var maybeNull: String? = "baz" neverNull = null // Compiler error neverNull.length // Guaranteed OK maybeNull.length // Compiler error maybeNull?.length // Possible null instead of length maybeNull!!.length // Possible NPE var valueOrSadness = maybeNull ?: "it was null !" Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 24
  • 25. Null safety var neverNull: String = "foobar" var maybeNull: String? = "baz" neverNull = null // Compiler error neverNull.length // Guaranteed OK maybeNull.length // Compiler error maybeNull?.length // Possible null instead of length maybeNull!!.length // Possible NPE var valueOrSadness = maybeNull ?: "it was null !" Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 25
  • 26. Null safety var neverNull: String = "foobar" var maybeNull: String? = "baz" neverNull = null // Compiler error neverNull.length // Guaranteed OK maybeNull.length // Compiler error maybeNull?.length // Possible null instead of length maybeNull!!.length // Possible NPE var valueOrSadness = maybeNull ?: "it was null !" Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 26
  • 27. Null safety var neverNull: String = "foobar" var maybeNull: String? = "baz" neverNull = null // Compiler error neverNull.length // Guaranteed OK maybeNull.length // Compiler error maybeNull?.length // Possible null instead of length maybeNull!!.length // Possible NPE var valueOrSadness = maybeNull ?: "it was null !" Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 27
  • 28. Null tracking if (maybeNull != null && maybeNull.length > 5) { // maybeNull guaranteed to not be print("It is ${maybeNull.length} characters") } else { print("The variable is null !") } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 28
  • 29. Type inference fun returnsAListOfStrings(): List<String> { return listOf("foo", "bar") } // Java // final List<String> listOfStrings = returnsAListOfStrings(); // final String firstString = listOfStrings[0]; val listOfStrings = returnsAListOfStrings() val firstString = listOfStrings[0] Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 29
  • 30. Type inference fun returnsAListOfStrings(): List<String> { return listOf("foo", "bar") } // Java // final List<String> listOfStrings = returnsAListOfStrings(); // final String firstString = listOfStrings[0]; val listOfStrings = returnsAListOfStrings() val firstString = listOfStrings[0] Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 30
  • 31. Type inference fun returnsAListOfStrings(): List<String> { return listOf("foo", "bar") } // Java // final List<String> listOfStrings = returnsAListOfStrings(); // final String firstString = listOfStrings[0]; val listOfStrings = returnsAListOfStrings() val firstString = listOfStrings[0] Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 31
  • 32. POJO public class Pagechat { private final int id; private final String url; private final boolean fresh; public Pagechat(int id, String url, boolean fresh) { this.id = id; this.url = url; this.fresh = fresh; } public int getId() { return id; } public String getUrl() { return url; } public boolean getFresh() { return fresh; } public boolean equals(Object obj) { … } public int hashCode() { … } public String toString() { … } } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 32
  • 33. Data class (POJO equivalent) data class Pagechat(val id: Int, val url: String, val fresh: Boolean) Free stuff: - Accessors for fields; setters for vars - equals()/hashCode() - toString() - copy() Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 33
  • 34. Param checking in Kotlin fun updateAddress(newAddress: UpdateAddress): Boolean { // Guaranteed to be well-formed ... } data class UpdateAddress(val userId: Int, val address: Address ) data class Address(val number: Int, val street: String, val zip: Int) Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 34
  • 35. Using the copy constructor data class Pagechat(val id: Int, val url: String, val fresh: Boolean) ... fun createPagechat(url: String, fresh: Boolean): Pagechat { val pagechat = Pagechat(0, "http://foobar.com", true) // { id: 0, url: "http://foobar.com", fresh: true } val newId = dao.insert(pagechat) return pagechat.copy(id = newId) // { id: $newId, url: "http://foobar.com", fresh: true } } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 35
  • 36. Be!er switch statement (when) when (view) { is TextView -> toast(view.text) is RecyclerView -> toast("Item count = ${view.adapter.itemCount}") is SearchView -> toast("Current query: ${view.query}") else -> toast("View type not supported") } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 36
  • 37. Named arguments & defaults data class User(name: String, email: String, admin: Boolean = false) ... val drew = User("Drew", "drew@dinomite.net") // drew.admin is false val plague = User("The Plague", "babbage@ellingson.com", true) // plague.admin is true val named = User(email = "foo@bar.com", name = "Foo Bar") Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 37
  • 38. Tail recursion4 tailrec fun findFixPoint(x: Double = 1.0): Double { val cosine = Math.cos(x) if (x == cosine) { return x } else { return findFixPoint(cosine) } } // Shorter tailrec fun findFixPoint(x: Double = 1.0): Double = if (x == Math.cos(x)) x else findFixPoint(Math.cos(x)) 4 https://kotlinlang.org/docs/reference/functions.html#tail-recursive-functions Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 38
  • 39. Be!er enums enum class Matcher(val cssQuery: String, val attr: String) { OG_TITLE("meta[property=og:title]", "content"), META_TITLE("meta[name=title]", "content"), TITLE("title", null) } Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 39
  • 40. Be!er streams syntax val cars = mapOf( 2 to "Vandoorne", 3 to "Ricciardo", 5 to "Vettel", 7 to "Räikkönen", … ) val qualified = listOf(44, 5, 77, 7, 33, …) ... val grid = qualified.map { cars[it] } // Java: qualified.stream().map(e -> cars.get(e)) // [Hamilton, Vettel, Bottas, Räikkönen, …] Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 40
  • 42. How do I use it? Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 42
  • 43. build.gradle buildscript { repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.2" } } apply plugin: 'kotlin' Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 43
  • 44. Tell me more - Kotlin docs—https://kotlinlang.org/docs/reference/ - Try Kotlin in your browser—http://try.kotlinlang.org/ - My Kotlin repos—https://github.com/dinomite - Dynamic vs Static—https://youtu.be/Uxl_X3zXVAM Drew Stephens <drew@dinomite.net> @dinomite https://forumforall.net Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 44
  • 46. JSON3 { "id": 7, "email": "drew@dinomite.net" } data class User(id: Int, email: String) 3 https://medium.com/square-corner-blog/kotlins-a-great-language-for-json-fcd6ef99256b Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 46
  • 47. Simpler lambdas takesLambdaArg(e -> e.getValue()) takesLambdaArg({ it.getValue() }) Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 47
  • 48. String interpolation val foo = "foobar" println("The variable is $foo") // The variable is foobar Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 48
  • 49. Embracing null2 fun findUser(id: Int): User? ... findUser(7)?.let { // Only executes if user exists it.transmogrify(42) } 2 http://beust.com/weblog/2016/01/14/a-close-look-at-kotlins-let/ Drew Stephens • <drew@dinomite.net> • github.com/dinomite/talks 49