SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
Kotlin: a better Java
Nils Breunese
March 2016
Java
• Proven technology
• Stable
• Good performance
• Lots of libraries
• Good tooling support
• But...
Kotlin
Imagine a better
Java
No Semicolons
// Java
System.out.println("Hello world!);
// Kotlin
println("Hello world!")
No Primitives
// Java
int a = 1;
short s = 2;
boolean b;
// Kotlin
var a: Int = 1
var s: Short = 2
var b: Boolean
No 'new'
// Java
Boa boa = new Boa();
// Kotlin
val boa = Boa()
No Checked Exceptions
// Java code often looks like this
StringBuilder sb = new StringBuilder();
try {
sb.append(message);
} catch (IOException ignored) {
// Must be safe
}
// Kotlin has no checked exceptions
Type Declaration
// Java
Int a = 1;
String b = "b";
Program p;
// Kotlin
var a: Int = 1
var b: String = "b"
var p: Program
Type Inference
// Java
Int a = 1;
String b = "b";
Program p;
// Kotlin
var a = 1
var b = "b"
var p: Program
Immutable Values
// Java
final Int a = 1;
final String b = "b";
final Program p;
// Kotlin
val a = 1
val b = "b"
val p: Program
String Templates
// Java
String s = String.format("%s has %d apples",
name, count);
// Kotlin
val s = "$name has $count apples"
Raw Strings
// Java doesn't have raw strings
String text =
"n for (c in "foo"n print(c)n";
// Kotlin
val text = """
for (c in "foo")
print(c)
"""
Functions
// Java
String getName(Person person) {
return person.getName();
}
// Kotlin
fun getName(person: Person): String {
return person.name
}
Expression Body
// Java
Int sum(Int a, Int b) {
return a + b;
}
// Kotlin
fun sum(a: Int, b: Int): Int {
return a + b
}
Expression Body
// Java
Int sum(Int a, Int b) {
return a + b;
}
// Kotlin
fun sum(a: Int, b: Int): Int {
return a + b
}
fun sum(a: Int, b: Int) = a + b
Extension Functions
// Kotlin
fun String.spaceToCamelCase() { ... }
"Convert to camelcase".spaceToCamelCase()
If Expression
// Java
Int max;
if (a > b) { max = a } else { max = b };
// OK, Java has a ternary operator
Int max = a > b ? a : b;
// Kotlin's 'if' is an expression,
// so it has a value
val max = if (a > b) a else b
When Expression
// Java has switch
switch(x) {
case 1: log.info("x == 1"); break;
case 2: log.info("x == 2"); break;
default:
log.info("x is neither 1 nor 2");
}
// Kotlin's when is cleaner and more powerful
when (x) {
1 -> log.info("x == 1")
2 -> log.info("x == 2")
else -> log.info("x is neither 1 nor 2")
}
When Expression
when (x) {
in 0,1 -> print("x is too low")
in 2..10 -> print("x is in range")
!in 10..20 -> print("x outside range")
parseInt(s) -> print("s encodes x")
is Program -> print("It's a program!")
else -> print("None of the above")
}
Try Expression
// In Java 'try' is not an expression
Int a = null;
try {
a = parseInt(input);
} catch (NumberFormatException ignored) {}
// Kotlin
val a: Int? =
try { parseInt(input) }
catch (e: NumberFormatException) { null }
Nullable Types
// Java types can be null
Program program = null;
ProgramType type = program.getType();
==> NullPointerException when executed
// Kotlin
var program: Program = null
==> Compiler error, type not nullable
var program: Program? = null
val type = program?.type
Not Null Shorthand
// Java
Program p = mediaService.getProgram(123);
String programTypeName = null;
if (p != null && p.getType() != null) {
programTypeName = p.getType().getName();
}
// Kotlin
val p = mediaService.getProgram(123)
val typeName = p?.type?.name
Not Null Or Else
// Java
File[] files = new File("test").listFiles();
int count = files != null ? files.size : 0;
// Kotlin
val files = File("test").listFiles()
val count = files?.size ?: 0
Ranges
// Java
IntStream.rangeClosed(1, 5)
.forEach(x -> ...);
// Kotlin
for (x in 1..5) { ... }
Ranges
// Kotlin
if (x in 1..y-1) { ... }
if (x !in 0..array.lastIndex) { ... }
Collections
// Java
for (String name : names) { ... }
if (names.contains(text)) { ... }
// Kotlin
for (name in names) { ... }
if (text in names) { ... }
Read-Only Collections
// Kotlin encourages read-only collections
listOf(1, 2, 3, 4)
mapOf(1 to "A", 2 to "B")
setOf("Hello", "World")
Collections
// But it’s easy to create mutable
// collections too
arrayListOf("Hello", "World")
linkedListOf("Hello", "World")
hashMapOf(1 to "A", 2 to "B")
linkedMapOf(1 to "A", 2 to "B")
sortedMapOf(1 to "A", 2 to "B")
sortedSetOf(1, 2, 3)
Maps
// Java
System.out.println(map.get("key"));
map.put("key", value);
for (Map.Entry<K, V> entry :
map.entrySet())
{ ... }
// Kotlin
println(map["key"])
map["key"] = value
for ((k, v) in map) { ... }
Lambdas
names.stream()
.filter(n -> n.startWith("A"))
.sorted((n1, n1) ->
Integer.compare(n1.length(),
n2.length()))
.collect(Collectors.toList());
names
.filter { n -> n.startsWith("A") }
.sortedBy { n -> n.length }
.map { n -> n.toUpperCase() }
Lambdas
names.stream()
.filter(n -> n.startWith("A"))
.sorted((n1, n1) ->
Integer.compare(n1.length(),
n2.length()))
.collect(Collectors.toList());
names
.filter { it.startsWith("A") }
.sortedBy { it.length }
.map { it.toUpperCase() }
Classes
// Java
class Person {
String firstName;
Person(String firstName) {
this.firstName = firstName;
}
}
// Kotlin class with primary constructor
class Person(firstName: String)
Classes
// Java
final class Unextendable { ... }
// Kotlin classes are final by default
class Unextendable { ... }
// Declare as 'open' to allow extension
open class Extendable { ... }
// Abstract classes are automatically open
abstract class Abstract { ... }
Sealed Classes
// Kotlin sealed class restricts hierarchy
sealed class Expr {
class Const(val number: Double) : Expr()
class Sum(val e1: Expr,
val e2: Expr) : Expr()
object NotANumber : Expr()
}
when(expr) {
is Const -> expr.number
is Sum -> eval(expr.e1) + eval(expr.e2)
NotANumber -> Double.NaN // no 'else'
}
DTO's
// Java
class Broadcaster {
final String name;
Broadcaster(String n) { name = n; }
String getName() { return name; }
void setName(String n) { name = n; }
int equals() { ... }
hashCode() { ... }
toString() { ... }
copy() { ... }
}
DTO's
// Kotlin
data class Broadcaster(var name: String)
// Using 'val' omits the setter
data class Broadcaster(val name: String)
Default Arguments
// Java doesn't have default arguments
void foo(Int a, String b) {
if (a == null) { a = 0; }
if (b == null) { b = ""; }
(...)
}
// Kotlin
fun foo(a: Int = 0, b: String = "") {
(...)
}
Named Arguments
// Kotlin
fun reformat(
str: String,
normalizeCase: Boolean = true,
upperCaseFirstLetter: Boolean = true,
divideByCamelHumps: Boolean = false,
wordSeparator: Char = ' ') { ... }
reformat(str, wordSeparator = '_')
Smart Cast
// Java
Object obj = getObject();
if (obj instanceof String) {
return ((String)obj).length()
}
// Kotlin
val obj = getObject()
if (obj is String) {
return obj.length
}
JavaScript
Kotlin can also target JavaScript
instead of the Java Virtual Machine
Etc., etc.
Properties, better generics,
delegation, operator overloading, tail
recursion, infix functions,
destructuring, type-safe builders,
with, object expressions, object
declarations, companion objects,
extension properties, companion object
extensions, vararg modifier, ...
Getting started
• kotlinlang.org / try.kotlinlang.org
• Kotlin Koans
• Kotlin Educational Plugin (IDEA 2016.1)
• Plugins for Maven and Gradle, Ant tasks
(you can mix Java & Kotlin!)
• Slack: kotlinslackin.herokuapp.com

Weitere ähnliche Inhalte

Was ist angesagt?

Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinAndrey Breslav
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan s.r.o.
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Sunghyouk Bae
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyHaim Yadid
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and SimpleBen Mabey
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designAndrey Breslav
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of androidDJ Rausch
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
 
Android dev toolbox - Shem Magnezi, WeWork
Android dev toolbox - Shem Magnezi, WeWorkAndroid dev toolbox - Shem Magnezi, WeWork
Android dev toolbox - Shem Magnezi, WeWorkDroidConTLV
 

Was ist angesagt? (20)

Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Introduction to Kotlin
Introduction to KotlinIntroduction to Kotlin
Introduction to Kotlin
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, Seriously
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and Simple
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language design
 
Kotlin
KotlinKotlin
Kotlin
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of android
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
Android dev toolbox - Shem Magnezi, WeWork
Android dev toolbox - Shem Magnezi, WeWorkAndroid dev toolbox - Shem Magnezi, WeWork
Android dev toolbox - Shem Magnezi, WeWork
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 

Ähnlich wie Kotlin: a better Java

What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java DevelopersChristoph Pickl
 
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdfAndrey Breslav
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
 
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
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance Coder Tech
 
Kotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonKotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonEd Austin
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlinSergey Bandysik
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does notSergey Bandysik
 

Ähnlich wie Kotlin: a better Java (20)

What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
 
Kotlin
KotlinKotlin
Kotlin
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Introduction kot iin
Introduction kot iinIntroduction kot iin
Introduction kot iin
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
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 for curious
Scala for curiousScala for curious
Scala for curious
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 
Kotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonKotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparison
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlin
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does not
 

Mehr von Nils Breunese

Improving Performance and Flexibility of Content Listings Using Criteria API
Improving Performance and Flexibility of Content Listings Using Criteria APIImproving Performance and Flexibility of Content Listings Using Criteria API
Improving Performance and Flexibility of Content Listings Using Criteria APINils Breunese
 
HTTP API for Free? Check out CouchDB
HTTP API for Free? Check out CouchDBHTTP API for Free? Check out CouchDB
HTTP API for Free? Check out CouchDBNils Breunese
 
Website-tool: CMS of Framework
Website-tool: CMS of FrameworkWebsite-tool: CMS of Framework
Website-tool: CMS of FrameworkNils Breunese
 

Mehr von Nils Breunese (6)

Improving Performance and Flexibility of Content Listings Using Criteria API
Improving Performance and Flexibility of Content Listings Using Criteria APIImproving Performance and Flexibility of Content Listings Using Criteria API
Improving Performance and Flexibility of Content Listings Using Criteria API
 
NLJUG J-Fall 2011
NLJUG J-Fall 2011NLJUG J-Fall 2011
NLJUG J-Fall 2011
 
NLJUG J-Fall 2011
NLJUG J-Fall 2011NLJUG J-Fall 2011
NLJUG J-Fall 2011
 
HTTP API for Free? Check out CouchDB
HTTP API for Free? Check out CouchDBHTTP API for Free? Check out CouchDB
HTTP API for Free? Check out CouchDB
 
Website-tool: CMS of Framework
Website-tool: CMS of FrameworkWebsite-tool: CMS of Framework
Website-tool: CMS of Framework
 
WSO2 Mashup Server
WSO2 Mashup ServerWSO2 Mashup Server
WSO2 Mashup Server
 

Kürzlich hochgeladen

KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 

Kürzlich hochgeladen (20)

KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 

Kotlin: a better Java

  • 1. Kotlin: a better Java Nils Breunese March 2016
  • 2. Java • Proven technology • Stable • Good performance • Lots of libraries • Good tooling support • But...
  • 4. No Semicolons // Java System.out.println("Hello world!); // Kotlin println("Hello world!")
  • 5. No Primitives // Java int a = 1; short s = 2; boolean b; // Kotlin var a: Int = 1 var s: Short = 2 var b: Boolean
  • 6. No 'new' // Java Boa boa = new Boa(); // Kotlin val boa = Boa()
  • 7. No Checked Exceptions // Java code often looks like this StringBuilder sb = new StringBuilder(); try { sb.append(message); } catch (IOException ignored) { // Must be safe } // Kotlin has no checked exceptions
  • 8. Type Declaration // Java Int a = 1; String b = "b"; Program p; // Kotlin var a: Int = 1 var b: String = "b" var p: Program
  • 9. Type Inference // Java Int a = 1; String b = "b"; Program p; // Kotlin var a = 1 var b = "b" var p: Program
  • 10. Immutable Values // Java final Int a = 1; final String b = "b"; final Program p; // Kotlin val a = 1 val b = "b" val p: Program
  • 11. String Templates // Java String s = String.format("%s has %d apples", name, count); // Kotlin val s = "$name has $count apples"
  • 12. Raw Strings // Java doesn't have raw strings String text = "n for (c in "foo"n print(c)n"; // Kotlin val text = """ for (c in "foo") print(c) """
  • 13. Functions // Java String getName(Person person) { return person.getName(); } // Kotlin fun getName(person: Person): String { return person.name }
  • 14. Expression Body // Java Int sum(Int a, Int b) { return a + b; } // Kotlin fun sum(a: Int, b: Int): Int { return a + b }
  • 15. Expression Body // Java Int sum(Int a, Int b) { return a + b; } // Kotlin fun sum(a: Int, b: Int): Int { return a + b } fun sum(a: Int, b: Int) = a + b
  • 16. Extension Functions // Kotlin fun String.spaceToCamelCase() { ... } "Convert to camelcase".spaceToCamelCase()
  • 17. If Expression // Java Int max; if (a > b) { max = a } else { max = b }; // OK, Java has a ternary operator Int max = a > b ? a : b; // Kotlin's 'if' is an expression, // so it has a value val max = if (a > b) a else b
  • 18. When Expression // Java has switch switch(x) { case 1: log.info("x == 1"); break; case 2: log.info("x == 2"); break; default: log.info("x is neither 1 nor 2"); } // Kotlin's when is cleaner and more powerful when (x) { 1 -> log.info("x == 1") 2 -> log.info("x == 2") else -> log.info("x is neither 1 nor 2") }
  • 19. When Expression when (x) { in 0,1 -> print("x is too low") in 2..10 -> print("x is in range") !in 10..20 -> print("x outside range") parseInt(s) -> print("s encodes x") is Program -> print("It's a program!") else -> print("None of the above") }
  • 20. Try Expression // In Java 'try' is not an expression Int a = null; try { a = parseInt(input); } catch (NumberFormatException ignored) {} // Kotlin val a: Int? = try { parseInt(input) } catch (e: NumberFormatException) { null }
  • 21. Nullable Types // Java types can be null Program program = null; ProgramType type = program.getType(); ==> NullPointerException when executed // Kotlin var program: Program = null ==> Compiler error, type not nullable var program: Program? = null val type = program?.type
  • 22. Not Null Shorthand // Java Program p = mediaService.getProgram(123); String programTypeName = null; if (p != null && p.getType() != null) { programTypeName = p.getType().getName(); } // Kotlin val p = mediaService.getProgram(123) val typeName = p?.type?.name
  • 23. Not Null Or Else // Java File[] files = new File("test").listFiles(); int count = files != null ? files.size : 0; // Kotlin val files = File("test").listFiles() val count = files?.size ?: 0
  • 24. Ranges // Java IntStream.rangeClosed(1, 5) .forEach(x -> ...); // Kotlin for (x in 1..5) { ... }
  • 25. Ranges // Kotlin if (x in 1..y-1) { ... } if (x !in 0..array.lastIndex) { ... }
  • 26. Collections // Java for (String name : names) { ... } if (names.contains(text)) { ... } // Kotlin for (name in names) { ... } if (text in names) { ... }
  • 27. Read-Only Collections // Kotlin encourages read-only collections listOf(1, 2, 3, 4) mapOf(1 to "A", 2 to "B") setOf("Hello", "World")
  • 28. Collections // But it’s easy to create mutable // collections too arrayListOf("Hello", "World") linkedListOf("Hello", "World") hashMapOf(1 to "A", 2 to "B") linkedMapOf(1 to "A", 2 to "B") sortedMapOf(1 to "A", 2 to "B") sortedSetOf(1, 2, 3)
  • 29. Maps // Java System.out.println(map.get("key")); map.put("key", value); for (Map.Entry<K, V> entry : map.entrySet()) { ... } // Kotlin println(map["key"]) map["key"] = value for ((k, v) in map) { ... }
  • 30. Lambdas names.stream() .filter(n -> n.startWith("A")) .sorted((n1, n1) -> Integer.compare(n1.length(), n2.length())) .collect(Collectors.toList()); names .filter { n -> n.startsWith("A") } .sortedBy { n -> n.length } .map { n -> n.toUpperCase() }
  • 31. Lambdas names.stream() .filter(n -> n.startWith("A")) .sorted((n1, n1) -> Integer.compare(n1.length(), n2.length())) .collect(Collectors.toList()); names .filter { it.startsWith("A") } .sortedBy { it.length } .map { it.toUpperCase() }
  • 32. Classes // Java class Person { String firstName; Person(String firstName) { this.firstName = firstName; } } // Kotlin class with primary constructor class Person(firstName: String)
  • 33. Classes // Java final class Unextendable { ... } // Kotlin classes are final by default class Unextendable { ... } // Declare as 'open' to allow extension open class Extendable { ... } // Abstract classes are automatically open abstract class Abstract { ... }
  • 34. Sealed Classes // Kotlin sealed class restricts hierarchy sealed class Expr { class Const(val number: Double) : Expr() class Sum(val e1: Expr, val e2: Expr) : Expr() object NotANumber : Expr() } when(expr) { is Const -> expr.number is Sum -> eval(expr.e1) + eval(expr.e2) NotANumber -> Double.NaN // no 'else' }
  • 35. DTO's // Java class Broadcaster { final String name; Broadcaster(String n) { name = n; } String getName() { return name; } void setName(String n) { name = n; } int equals() { ... } hashCode() { ... } toString() { ... } copy() { ... } }
  • 36. DTO's // Kotlin data class Broadcaster(var name: String) // Using 'val' omits the setter data class Broadcaster(val name: String)
  • 37. Default Arguments // Java doesn't have default arguments void foo(Int a, String b) { if (a == null) { a = 0; } if (b == null) { b = ""; } (...) } // Kotlin fun foo(a: Int = 0, b: String = "") { (...) }
  • 38. Named Arguments // Kotlin fun reformat( str: String, normalizeCase: Boolean = true, upperCaseFirstLetter: Boolean = true, divideByCamelHumps: Boolean = false, wordSeparator: Char = ' ') { ... } reformat(str, wordSeparator = '_')
  • 39. Smart Cast // Java Object obj = getObject(); if (obj instanceof String) { return ((String)obj).length() } // Kotlin val obj = getObject() if (obj is String) { return obj.length }
  • 40. JavaScript Kotlin can also target JavaScript instead of the Java Virtual Machine
  • 41. Etc., etc. Properties, better generics, delegation, operator overloading, tail recursion, infix functions, destructuring, type-safe builders, with, object expressions, object declarations, companion objects, extension properties, companion object extensions, vararg modifier, ...
  • 42. Getting started • kotlinlang.org / try.kotlinlang.org • Kotlin Koans • Kotlin Educational Plugin (IDEA 2016.1) • Plugins for Maven and Gradle, Ant tasks (you can mix Java & Kotlin!) • Slack: kotlinslackin.herokuapp.com