SlideShare a Scribd company logo
1 of 16
Download to read offline
7 Sins of fixed in otlin
Made with ❤ and ♫ Twitter @lucaguada
● Java/JS developer
● Poem performer
● Mountain biker
● Blade Runner
● DC/Manga Comicbooks reader
● Go Nagai Animes watcher
● PS4 gamer
● Vanilla Pudding eater
● Ellen Page lover (well I wish...)
Luca Guadagnini
@lucaguada
@tryIO
who the hell… ?
public final class Optional<T> {
private static final Optional<?> EMPTY = new Optional<>();
private final T value;
private Optional() { this.value = null; }
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
private Optional(T value) { this.value = Objects.requireNonNull(value);
}
…
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
…
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent()) return this;
else return predicate.test(value) ? this : empty();
}
}
Lust: “If you wanna be bad, you gotta be good”
● public not default?
● EMPTY encapsulated within?
● iaargh!! an @Annotation!
● casting style stuck to 90’s
● runtime null-checking
● methods are too long to
write
● public and final class by default!
● always know when a value is nullable
● inline method definitions!
● semi-colon (;) no-more!
● static methods no-more!
● new keyword no more! just call
constructor as-is
● lambda-expr. are first-class citizen
● typealias!!
● out part of new generics system (too
long to explain it, next time ;) )
Lust: Talk to me pleasantly
// Kotlin 1.1
typealias Predicate = (T) -> Boolean
class Optional<out T>(private val value:T?) {
private constructor(): this(null)
…
fun filter(predicate: Predicate) =
if (value?.let(predicate) ?: false) this else
Optional<T>()
fun get() = this.value ?: throw IllegalStateException()
…
}
val o = Optional(“Hello Kotlin”)
val kotlin = o.filter { it.contains(“Kotlin”) }.get()
println(“Java? $kotlin”)
Gluttony: Static methods
// Java 6/7
public class NumUtils {
public static int max(int… nums) {
…
}
}
// Java 8
public interface NumUtils {
static int max(int… nums) {
…
}
}
int[] nums = new int[] {1, 2, 3};
int max = NumUtils.max(nums);
● ugly procedural style
● code-smell
● silly class/interface names
● lead to a ton of duplicated code
● no use case, just a helper
● hard to understand where it’s used
Gluttony: Extension methods
// Kotlin 1.1
fun Array<Int>.max():Int {
...
}
val nums = arrayOf(1, 2, 3)
val max = nums.max()
● Array is an object, so let’s use it in
that way!
● max is a method which has decorated
the Array object in order to extend it
● with a single dot we can know if
something is already implemented,
without seek for a particular method
through every single package to find
that particular SomethingUtils class
● Self-documented: “I find max-number in
the array you’re actually using, not
any unknown array which I don’t know
where it comes from”
● a couple of minutes to write
● two properties, then 4 methods!
before Java7 has been proposed
«property» syntax… but it was
rejected
● any Printable implementation must
handle IOException
● each interface/class, we have a
file
● primary constructors with DI are
not standard
● still possible to define abstract
interfaces, because of Java 1.0!!
Cupidity: Conservative Tradition
public abstract interface Printable {
void print() throws IOException;
}
public class Book implements Printable {
private String title;
private String text;
public Book(String title, String text) {
this.title = title;
this.text = text;
}
// getters and setters - 4 methods by the way
@Override
public void print() throws IOException {
// print on something that may throw an IOException, but is
that
// really needed?
}
// and of course toString, equals, hashcode overriding too
}
Cupidity: Progressive Legacy
● less than 5 secs
● properties are implicit
● : inspired by C++/C#
● all exceptions are unchecked
● everything can be defined in one
single file
● by default all classes are Closed
for modification and Open for
extendibility
interface Printable {
fun print()
}
class Book(var title:String, var text:String) : Printable {
override fun print() {
…
}
}
Sorrow: Java Bean
public class Book {
private String title;
private String text;
public Book() {}
public Book(String title, String text) { … }
public void setTitle(String title) { this.title = title; }
public String getTitle() { return this.title; }
public void setText(String text) { this.text = text; }
public String getText() { return this.text; }
@Override public String toString() {
return “Title: ” + title + “ Text: ” + text;
}
@Override public boolean equals(Object obj) {
Book b = (Book) obj;
return title.equals(b.getTitle()) && text.equals(b.getText());
}
@Override public int hashcode() { return Objects.hash(title, text);
}
}
● it’s so 2000! (JDK 1.3)
● 2 fields, so 4 methods!
● default constructor must be
there!
● implicit extension of
java.lang.Object
● 1 minute to write a C-struct
● a hell lock-in to JEE
frameworks! even Spring is
going far away from this,
Hibernate as well
Sorrow: Java Bean in Data class
// Kotlin 1.1 - first step
data class Book(
var title:String,
var text:String
)
// second step
data class Book(var title:String, var text:String) {
constructor()
}
// but it won’t compile, Kotlin forces you to call the primary c.
data class Book(var title:String, var text:String) {
constructor(): this(“”, “”)
}
● inspired by Scala
● properties implicit
implementation
● primary c. is the real
constructor you actually need
● you can define yours, but
you’re forced to call the
primary one (❤)
● java.lang.Object methods
overrided by Kotlin (❤)
● the copy-method implemented
by Kotlin is a gift from
Heaven
Pride: Null Pointer Exception
public class Book {
private Writer writer;
...
}
public class Writer {
private String fullName;
...
}
public String getUpperCasedWriter(Book book) {
return book getWriter() getFullName() toUpperCase();
}
public String getUpperCasedWriter(Book book) {
if (book != null
&& book.getWriter() != null
&& book.getWriter().getFullName() != null)
{
return book.getWriter().getFullName().toUpperCase();
}
return null;
}
● null is part of your type-system!
● Null Pointer Exception?!? Java has
nothing to do with pointers! C++ and
Borland Turbo Pascal 7.0 does
● how can I express required fields? if
you don’t use primitive types, you
can’t actually (just with runtime
checking)
● or you can use @Annotations! for God’s
sake, don’t
● in Java8 you can use Optional to
mitigate NPE, but few understand it
Pride: Elvis to the rescue!
// Kotlin 1.1
data class Book(var writer:Writer)
data class Writer(var fullName:String)
fun getUpperCasedWriter(book:Book):String =
book.writer.fullName.toUpperCase()
// hence
var mobydick:Book? = Book(Writer(“Herman Mellvile”))
getUpperCasedWriter(mobydick) // won’t compile! since mobydick
is nullable and parameter is not
var bartleby:Book = Book(Writer(“Herman Mellvile”))
getUpperCasedWriter(bartleby) // no problem ❤
● null is still part of your type
system, but only if you want it and
it’s much more handleable anyway
● you can define required and
non-required properties/parameters
● ? in called properties/methods is the
Elvis-operator, if null-check fails,
null will be returned immediately and
no NPE
● no @Annotations used, no Optional
pattern needed (but you can use it
anyway with takeIf and let functional
patterns)
Wrath: Checked and Unchecked Exceptions
// Java
// I want to sleep for a while but not more than 10secs
public void sleepFor(long mills) {
if (mills <= 10000) {
Thread.sleep(mills);
} else {
throw new IllegalArgumentException();
}
}
// sorry compile error, you need to catch InterruptException
public void sleepFor(long mills) {
try {
if (mills <= 10000) {
Thread.sleep(mills);
} else {
throw new IllegalArgumentException();
}
} catch (InterruptException ie) {
// log and re-throw an unchecked exception
}
}
● Checked Exception: any exception that
extends java.lang.Exception;
InterruptException is a Checked
Exception (catch it!)
● Unchecked Exception: any exception
that extends
java.lang.RuntimeException;
IllegalArgumentException is an
Unchecked Exception (no need to catch
it!)
● the more you handle them, the more
code is bloated, the more you’re gonna
be crazy!
Wrath: Exception is Nothing
// Kotlin 1.1
// the solution in Kotlin
fun sleepFor(mills:Long) =
if (mills <= 10000) Thread.sleep(mills)
else throw IllegalArgumentException()
// not a valid parameter
fun notValidParameter():Nothing = throw IllegalArgumentException()
fun sleepFor(mills:Long) =
if (mills <= 1000) Thread.sleep(mills)
else notValidParameter()
● There’s no checked-exception
in Kotlin
● throw keyword has a
different meaning: retrieves
a type named Nothing, if
exception is created
● Nothing says “if I’m
retrieved, runtime-flow
stops”
Sloth: Enterprise or Community?
+ huge ecosystem
+ 1st lang in the world
+ nerdy then Oracle
+ OpenJDK free and open
+ JVM rocks
- Oracle
- no one uses JEE
- OracleJDK not tot.free
- Enterprise driven
- Java9 delay (againx3)
Sloth: Enterprise or Community?
+ Java interoperability
+ mix obj. and func.
+ adopted by Piv./Google
+ community driven
+ just take 1h to learn
- func. not for all
- Intellij lock-in (?)
- community driven
- very fast progression
can you keep up?

More Related Content

What's hot

Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Chang W. Doh
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahNick Plante
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеSergey Platonov
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Oky Firmansyah
 
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
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Omar Miatello
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Java 7 Language Enhancement
Java 7 Language EnhancementJava 7 Language Enhancement
Java 7 Language Enhancementmuthusvm
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018 Codemotion
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java DevelopersChristoph Pickl
 

What's hot (20)

Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)
 
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
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Java 7 Language Enhancement
Java 7 Language EnhancementJava 7 Language Enhancement
Java 7 Language Enhancement
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 

Similar to 7 Sins of Java fixed in Kotlin

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android DevelopmentSpeck&Tech
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaDILo Surabaya
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaKonrad Malawski
 
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
 
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
 
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
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 
BangaloreJUG introduction to kotlin
BangaloreJUG   introduction to kotlinBangaloreJUG   introduction to kotlin
BangaloreJUG introduction to kotlinChandra Sekhar Nayak
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlinvriddhigupta
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехСбертех | SberTech
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insAndrew Dupont
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt FaluoticoWithTheBest
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 

Similar to 7 Sins of Java fixed in Kotlin (20)

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo Surabaya
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
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
 
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)
 
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...
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
BangaloreJUG introduction to kotlin
BangaloreJUG   introduction to kotlinBangaloreJUG   introduction to kotlin
BangaloreJUG introduction to kotlin
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt Faluotico
 
Kotlin intro
Kotlin introKotlin intro
Kotlin intro
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
Clojure Small Intro
Clojure Small IntroClojure Small Intro
Clojure Small Intro
 

Recently uploaded

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Recently uploaded (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

7 Sins of Java fixed in Kotlin

  • 1. 7 Sins of fixed in otlin Made with ❤ and ♫ Twitter @lucaguada
  • 2. ● Java/JS developer ● Poem performer ● Mountain biker ● Blade Runner ● DC/Manga Comicbooks reader ● Go Nagai Animes watcher ● PS4 gamer ● Vanilla Pudding eater ● Ellen Page lover (well I wish...) Luca Guadagnini @lucaguada @tryIO who the hell… ?
  • 3. public final class Optional<T> { private static final Optional<?> EMPTY = new Optional<>(); private final T value; private Optional() { this.value = null; } public static<T> Optional<T> empty() { @SuppressWarnings("unchecked") Optional<T> t = (Optional<T>) EMPTY; return t; } private Optional(T value) { this.value = Objects.requireNonNull(value); } … public static <T> Optional<T> ofNullable(T value) { return value == null ? empty() : of(value); } … public Optional<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate); if (!isPresent()) return this; else return predicate.test(value) ? this : empty(); } } Lust: “If you wanna be bad, you gotta be good” ● public not default? ● EMPTY encapsulated within? ● iaargh!! an @Annotation! ● casting style stuck to 90’s ● runtime null-checking ● methods are too long to write
  • 4. ● public and final class by default! ● always know when a value is nullable ● inline method definitions! ● semi-colon (;) no-more! ● static methods no-more! ● new keyword no more! just call constructor as-is ● lambda-expr. are first-class citizen ● typealias!! ● out part of new generics system (too long to explain it, next time ;) ) Lust: Talk to me pleasantly // Kotlin 1.1 typealias Predicate = (T) -> Boolean class Optional<out T>(private val value:T?) { private constructor(): this(null) … fun filter(predicate: Predicate) = if (value?.let(predicate) ?: false) this else Optional<T>() fun get() = this.value ?: throw IllegalStateException() … } val o = Optional(“Hello Kotlin”) val kotlin = o.filter { it.contains(“Kotlin”) }.get() println(“Java? $kotlin”)
  • 5. Gluttony: Static methods // Java 6/7 public class NumUtils { public static int max(int… nums) { … } } // Java 8 public interface NumUtils { static int max(int… nums) { … } } int[] nums = new int[] {1, 2, 3}; int max = NumUtils.max(nums); ● ugly procedural style ● code-smell ● silly class/interface names ● lead to a ton of duplicated code ● no use case, just a helper ● hard to understand where it’s used
  • 6. Gluttony: Extension methods // Kotlin 1.1 fun Array<Int>.max():Int { ... } val nums = arrayOf(1, 2, 3) val max = nums.max() ● Array is an object, so let’s use it in that way! ● max is a method which has decorated the Array object in order to extend it ● with a single dot we can know if something is already implemented, without seek for a particular method through every single package to find that particular SomethingUtils class ● Self-documented: “I find max-number in the array you’re actually using, not any unknown array which I don’t know where it comes from”
  • 7. ● a couple of minutes to write ● two properties, then 4 methods! before Java7 has been proposed «property» syntax… but it was rejected ● any Printable implementation must handle IOException ● each interface/class, we have a file ● primary constructors with DI are not standard ● still possible to define abstract interfaces, because of Java 1.0!! Cupidity: Conservative Tradition public abstract interface Printable { void print() throws IOException; } public class Book implements Printable { private String title; private String text; public Book(String title, String text) { this.title = title; this.text = text; } // getters and setters - 4 methods by the way @Override public void print() throws IOException { // print on something that may throw an IOException, but is that // really needed? } // and of course toString, equals, hashcode overriding too }
  • 8. Cupidity: Progressive Legacy ● less than 5 secs ● properties are implicit ● : inspired by C++/C# ● all exceptions are unchecked ● everything can be defined in one single file ● by default all classes are Closed for modification and Open for extendibility interface Printable { fun print() } class Book(var title:String, var text:String) : Printable { override fun print() { … } }
  • 9. Sorrow: Java Bean public class Book { private String title; private String text; public Book() {} public Book(String title, String text) { … } public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } public void setText(String text) { this.text = text; } public String getText() { return this.text; } @Override public String toString() { return “Title: ” + title + “ Text: ” + text; } @Override public boolean equals(Object obj) { Book b = (Book) obj; return title.equals(b.getTitle()) && text.equals(b.getText()); } @Override public int hashcode() { return Objects.hash(title, text); } } ● it’s so 2000! (JDK 1.3) ● 2 fields, so 4 methods! ● default constructor must be there! ● implicit extension of java.lang.Object ● 1 minute to write a C-struct ● a hell lock-in to JEE frameworks! even Spring is going far away from this, Hibernate as well
  • 10. Sorrow: Java Bean in Data class // Kotlin 1.1 - first step data class Book( var title:String, var text:String ) // second step data class Book(var title:String, var text:String) { constructor() } // but it won’t compile, Kotlin forces you to call the primary c. data class Book(var title:String, var text:String) { constructor(): this(“”, “”) } ● inspired by Scala ● properties implicit implementation ● primary c. is the real constructor you actually need ● you can define yours, but you’re forced to call the primary one (❤) ● java.lang.Object methods overrided by Kotlin (❤) ● the copy-method implemented by Kotlin is a gift from Heaven
  • 11. Pride: Null Pointer Exception public class Book { private Writer writer; ... } public class Writer { private String fullName; ... } public String getUpperCasedWriter(Book book) { return book getWriter() getFullName() toUpperCase(); } public String getUpperCasedWriter(Book book) { if (book != null && book.getWriter() != null && book.getWriter().getFullName() != null) { return book.getWriter().getFullName().toUpperCase(); } return null; } ● null is part of your type-system! ● Null Pointer Exception?!? Java has nothing to do with pointers! C++ and Borland Turbo Pascal 7.0 does ● how can I express required fields? if you don’t use primitive types, you can’t actually (just with runtime checking) ● or you can use @Annotations! for God’s sake, don’t ● in Java8 you can use Optional to mitigate NPE, but few understand it
  • 12. Pride: Elvis to the rescue! // Kotlin 1.1 data class Book(var writer:Writer) data class Writer(var fullName:String) fun getUpperCasedWriter(book:Book):String = book.writer.fullName.toUpperCase() // hence var mobydick:Book? = Book(Writer(“Herman Mellvile”)) getUpperCasedWriter(mobydick) // won’t compile! since mobydick is nullable and parameter is not var bartleby:Book = Book(Writer(“Herman Mellvile”)) getUpperCasedWriter(bartleby) // no problem ❤ ● null is still part of your type system, but only if you want it and it’s much more handleable anyway ● you can define required and non-required properties/parameters ● ? in called properties/methods is the Elvis-operator, if null-check fails, null will be returned immediately and no NPE ● no @Annotations used, no Optional pattern needed (but you can use it anyway with takeIf and let functional patterns)
  • 13. Wrath: Checked and Unchecked Exceptions // Java // I want to sleep for a while but not more than 10secs public void sleepFor(long mills) { if (mills <= 10000) { Thread.sleep(mills); } else { throw new IllegalArgumentException(); } } // sorry compile error, you need to catch InterruptException public void sleepFor(long mills) { try { if (mills <= 10000) { Thread.sleep(mills); } else { throw new IllegalArgumentException(); } } catch (InterruptException ie) { // log and re-throw an unchecked exception } } ● Checked Exception: any exception that extends java.lang.Exception; InterruptException is a Checked Exception (catch it!) ● Unchecked Exception: any exception that extends java.lang.RuntimeException; IllegalArgumentException is an Unchecked Exception (no need to catch it!) ● the more you handle them, the more code is bloated, the more you’re gonna be crazy!
  • 14. Wrath: Exception is Nothing // Kotlin 1.1 // the solution in Kotlin fun sleepFor(mills:Long) = if (mills <= 10000) Thread.sleep(mills) else throw IllegalArgumentException() // not a valid parameter fun notValidParameter():Nothing = throw IllegalArgumentException() fun sleepFor(mills:Long) = if (mills <= 1000) Thread.sleep(mills) else notValidParameter() ● There’s no checked-exception in Kotlin ● throw keyword has a different meaning: retrieves a type named Nothing, if exception is created ● Nothing says “if I’m retrieved, runtime-flow stops”
  • 15. Sloth: Enterprise or Community? + huge ecosystem + 1st lang in the world + nerdy then Oracle + OpenJDK free and open + JVM rocks - Oracle - no one uses JEE - OracleJDK not tot.free - Enterprise driven - Java9 delay (againx3)
  • 16. Sloth: Enterprise or Community? + Java interoperability + mix obj. and func. + adopted by Piv./Google + community driven + just take 1h to learn - func. not for all - Intellij lock-in (?) - community driven - very fast progression can you keep up?