SlideShare a Scribd company logo
© Instil Software 2020
TypeScript vs KotlinJS
should you make the
switch?
@BoyleEamonn
Eamonn Boyle
eamonn.boyle@gearset.com
eamonn
garth
@GarthGilmour
Garth Gilmour
garth.gilmour@instil.co
– TS brings types and compilation to JS
– Improves upon the existing strengths of JS
– Makes us more productive and happy
– Leverages existing JS frameworks
– Interop with JS is a design goal
we love typescript
it solves real problems for us
– Kotlin improves upon Java in many ways
– Adds null safety, DSLs, coroutines etc...
– Makes us more productive and happy
– Leverages existing JVM frameworks
– But interop with Java is a design goal
we love kotlin
it solves real problems for us
JVM
Java
Bytecode
Kotlin
(JVM)
Kotlin
(JS)
Browser
JavaScript
Interpreter
Kotlin
(Native)
Machine Code
& Runtime
OS
Kotlin
(Android)
ART
Dalvik
Bytecode
experiment: is kotlinjs worth it?
– We are not using KotlinJS in production
– The code written has been for labs, workshops and talks
– Built several apps both TypeScript and KotlinJS
– Go beyond “hello world”
– Incorporate common JS libraries
– Compare the experience
– Tooling
– Language features
– Community
what problem does it solve?
creating a
kotlinjs react project
– Template project from IntelliJ
– Grade project using Kotlin DSL
– Easily integrate NPM packages
creating new project
the wizard
multiplatform libraries
COMMON
KOTLIN
KOTLIN ANDROID
KOTLIN JS
KOTLIN NATIVE
KOTLIN JVM
NATIVE
ARTEFACT
JS BUNDLE
JAR
standard library documentation
excellent compatibility docs
configuring the kotlin gradle dsl
plugins{
kotlin("js")version"1.6.21"
kotlin("plugin.serialization")version"1.6.21"
}
group="org.example"
version="1.0-SNAPSHOT"
valktorVersion="2.0.2"
repositories{ mavenCentral()}
dependencies{ ...}
configuring the kotlin gradle dsl
kotlin{
js(LEGACY){
binaries.executable()
browser{
commonWebpackConfig{
cssSupport.enabled=true
}
}
}
}
There is a new IR compiler
tasks in the kotlin gradle dsl
add multiplatform and kotlinjs packages
kotlinjs, multiplatform and npm
dependencies {
implementation("org.jetbrains.kotlin-wrappers:kotlin-react:17.0.2-pre.290-kotlin-1.6.10")
implementation("org.jetbrains.kotlin-wrappers:kotlin-react-dom:17.0.2-pre.290-kotlin-1.6.10")
implementation("org.jetbrains.kotlin-wrappers:kotlin-react-router-dom:6.3.0-pre.340-compat")
implementation("org.jetbrains.kotlin-wrappers:kotlin-react-css:17.0.2-pre.290-kotlin-1.6.10")
implementation(npm("bootstrap", "4.6.0"))
implementation(npm("jquery", "1.9.1- 3"))
implementation(npm("popper.js", "^1.16.1"))
}
what’s the code like
standard main function
funmain() {
valcontainer= document.createElement("div")
document.body!!.appendChild(container)
valapp=App.create()
render(app,container)
}
what’s the code like
easy access to browser apis
funmain() {
valcontainer= document.createElement("div")
document.body!!.appendChild(container)
valapp=App.create()
render(app,container)
}
what’s the code like
easy access to react library
valApp=FC<Props>("Application"){
BrowserRouter{
div{
p{ Link{ to="/hello”+"SimpleComponent”}}
}
div{
Routes{
Route{
// …
}
}
}
}
community
Round
1
its popularity continues to grow
rising star on language rankings
…
18 Kotlin
…
https://redmonk.com/sogrady/2021/03/01
/language-rankings-1-21/
The RedMonk
Programming Language
Rankings: January 2021
its popularity continues to grow
rising star on language rankings
https://insights.stackoverflow.com/survey/2020
Stack Overflow Developer
Survey 2020
Most Used Language
13th Kotlin
1st JavaScript
8th TypeScript
its popularity continues to grow
loved by its users
https://insights.stackoverflow.com/survey/2020
Stack Overflow Developer
Survey 2020
Most Loved Language
2nd TypeScript
4th Kotlin
10th JavaScript
1st Rust
TS is the largest alternative to JS
https://2021.stateofjs.com/en-US/
– TypeScript is more popular than KotlinJS
– As a superset of JS, reusing knowledge and assets is easier
– And the transition for JS developers to TS is easier
– TypeScript is well established in the JavaScript world
– Many libraries include TypeScript definitions
– DefinitelyTyped contains many more
community, maturity and support
typescript > kotlin
interop with javascript
Round
2
– Only a few first class wrappers provided
– It is easy to add NPM packages yourself
– But how easy is it to consume that code in Kotlin?
importing npm js packages
gradle dsl
dependencies {
. . .
implementation(npm("react-three-fiber", "4.2.20"))
implementation(npm("react-use-gesture", "7.0.15"))
implementation(npm("three", "0.119.1"))
}
really easy
external declarations
@file:JsModule("react-three-fiber")
@file:JsNonModule
...
external val Canvas: RClass<RProps>
external fun extend(objects: Any)
external fun useFrame(callback: (dynamic, Double) -> Unit)
external fun useThree(): dynamic
external interface PointerEvent {
val uv: Vector2
}
Specify the NPM package
Define any items you
wish to use
– Converts TypeScript d.ts files to Kotlin external declarations
– Still experimental
– At time of writing, on hold until IR compiler stabilises
dukat
automatic generation
https://kotlinlang.org/docs/js-external-declarations-with-dukat.html
– Command line tool
– Installable in isolation via npm
– Simply point to a .d.ts file and it will do the rest
dukat
usage
$ dukat index.d.ts index.module_my-library.kt
$ npm install dukat
dukat
export function getString(): string;
export function setString(input: string): void;
external fun getString(): String
external fun setString(input: String)
– Integrated into Gradle
– Generates definitions for configured packages
dukat
usage
Dukat tasks
-----------
generateExternals
generateExternalsIntegrated
dukat
export interface BasicInterface {
readonly field1: number;
method1(): boolean;
}
export function buildInterface(): BasicInterface;
export type ReadOnlyBasicInterface = Readonly<BasicInterface>;
external interface BasicInterface {
var field1: Number
fun method1(): Boolean
}
external fun buildInterface(): BasicInterface
typealias ReadOnlyBasicInterface = Readonly<BasicInterface>
– It’s a good help but has issues
– Limited by differences in the languages
– Not a seamless workflow
– This situation may improve as the tool and Kotlin evolves
not a silver bullet
square peg and a round hole
– KotlinJS supports a dynamic type
– You can use it in place of any type
– Assign it a value of any type
– Access and use members with any name
– Basically switches off type checking
– This can be used to quickly patch over APIs
dynamic
get out of jail type
external fun useFrame(callback: (dynamic, Double) -> Unit)
– Object literals are common in JavaScript
– KotlinJS has a helper function to create objects
– This is strongly typed (inferred) but requires fields to be var
jso
object literals in kotlinjs
Block(jso {
position = brick.location.toVector3()
color = brick.color
})
– We can embed JavaScript directly with the js function
– The code can even use Kotlin variables
– Must be a compile time constant
– Cannot be a runtime evaluated expression
js
embedding javascript
private fun getToken(): String? {
val tokenKey = TokenKey
return js("""
localStorage.getItem(tokenKey)
""")
}
– As a superset, TypeScript has to win this one
– The type system is geared to support JavaScript
– Lots of libraries already provide TypeScript definition files
– However, writing external declaration in KotlinJS is easy
– Dukat exists but has fundamental limitations
– You may have to write custom translation code on top
interop with javascript
typescript > kotlinjs
jsx vs dsl
Round
3
JSX
IN
TYPESCRIPT
JSX embeds markup
inside JS / TS code
export const TaskItem: FC<Props> = (props) =>
<tr key={props.taskIndex}>
<td>{props.task.text}</td>
<td>
<span onClick={props.onToggle}>
{pickIcon(props.task.done)}
</span>
</td>
</tr>
val TaskItem= functionalComponent<TaskItemProps>("TaskItem"){ props ->
tr{
td { +props.task.text }
td {
span {
+pickIcon(props.task.done)
}
attrs {
onClickFunction= { props.onToggle() }
}
}
}
}
fun RBuilder.TaskItem(task: Task) = child(TaskItem) {
attrs {
this.task = task
}
}
REACT
DSL
IN
KOTLIN
In Kotlin a DSL
provides equivalent
functionality
kotlin DSL’s are very cool
a major advantage
val TaskItem= functionalComponent<TaskItemProps>("TaskItem"){ props ->
tr{
td { +props.task.text }
td {
span {
+pickIcon(props.task.done)
}
attrs {
onClickFunction= { props.onToggle() }
}
}
}
}
fun RBuilder.TaskItem(task: Task) = child(TaskItem) {
attrs {
this.task = task
}
}
REACT
DSL
IN
KOTLIN
JSX is clearly a lot
simpler / shorter
Then they rewrote it
(without telling anyone)
val TaskItem=FC<TaskItemProps>("TaskItem"){props->
tr{
td{ +props.task.text}
td{
onClick={ props.onToggle()}
span{
+pickIcon(props.task.done)
}
}
}
}
REACT
DSL
IN
KOTLIN
val TaskItem=FC<TaskItemProps>("TaskItem"){props->
tr{
td{ +props.task.text}
td{
onClick={ props.onToggle()}
span{
+pickIcon(props.task.done)
}
}
}
}
REACT
DSL
IN
KOTLIN
Builder functions
not required
Many attributes
are cleaner
attrs section
is gone
The typing is ... imperfect
interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
max?: number | string;
min?: number | string;
value?: string | ReadonlyArray<string> | number;
...
}
Type union
type PropsWithChildren<P> = P & { children?: ReactNode };
Type intersection
// Type exports erased!
external fun interfaceUnionInput(input: First)
external fun interfaceUnionInput(input: Second)
external fun interfaceUnionOutput(): dynamic /* First | Second */
export type InterfaceUnion = First | Second;
export function interfaceUnionInput(input: InterfaceUnion): void;
export function interfaceUnionOutput(): InterfaceUnion;
Kotlin supports
proper overloads
Not supported on
the return type
external fun interfaceIntersectionInput(input: First /* First & Second */)
external fun interfaceIntersectionOutput(): First /* First & Second */
export type InterfaceIntersection = First & Second;
export function interfaceIntersectionInput(input: InterfaceIntersection): void;
export function interfaceIntersectionOutput(): InterfaceIntersection;
Intersection
dropped
mapped and conditional types
even more power in typescript
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type PromiseType<T extends Promise<any>> =
T extends Promise<infer U> ? U : never;
Type conditional
The languages are simply not
fully compatible
manual workarounds
useEffect
function useEffect(
effect: EffectCallback,
deps?: DependencyList
): void;
type EffectCallback = () => (void | Destructor);
type Destructor = () => void;
useEffect
union return workaround
fun useEffect(
dependencies: RDependenciesList? = null,
effect: () -> Unit
) {
// ...
}
fun useEffectWithCleanup(
dependencies: RDependenciesList? = null,
effect: () -> Rcleanup
) {
// ...
}
useEffect
or other patterns
useEffect { }
useEffect(dep1, dep2) { }
useEffectOnce { }
useEffectOnce {
cleanup {
// Clean up logic goes here
}
}
– Kotlin’s DSL support is a powerful general purpose tool
– But JSX is a single purpose solution that suits React better
– TypeScript’s advanced type system is very powerful
– Union, intersection and mapped types bring sanity to JS
– Kotlin types (unsurprisingly) sit awkwardly on top of JS
jsx vs dsl
typescript > kotlin
async await vs coroutines
Round
4
asynchronous programming
– Async await is a good async solution in JS & TS
– Engineered so it interops with Promises
– Succinct
promises and async/await
async function loadMap(url: string): Promise<void> {
const response = await fetch(url);
const map = await response.text();
// ...
}
coroutines
– Kotlin’s more general coroutines are better
– Works with other patterns than simply async
– In KotlinJS, it works easily with Promises
kotlin > typescript
suspend fun loadMap(url: String) {
val response = window.fetch(url).await()
val map = response.text().await()
// ...
}
coroutines
– Coroutines are more general and powerful
– They can be used with other patterns too
– With suspend functions we don’t need to “await”
kotlin > typescript
suspend fun loadMap(url: String) {
val map = client.get<String>(url)
// ...
}
Ktor Client
coroutines
– Coroutines can be applied to other patterns too
kotlin > typescript
fun infinite() = sequence {
var count = 0
while (true) {
yield(count++)
}
}
elegant syntax
Round
5
– Kotlin doesn’t have the ternary, but has more
– when for basic pattern matching
– if and when are expressions
– Unit instead of void
– Expression bodied functions
– This creates more symmetry in code
expressions
kotlin > typescript
typescript
chained ternaries
const App: FC = () => {
// ...
return (
<div>
// ...
{gameState === GameState.Start ? <StartScreen/> :
gameState === GameState.Playing ? <PlayingGame/> :
gameState === GameState.Dead ? <DeathScreen/> :
gameState === GameState.Win ? <WinScreen/> :
null}
</div>
);
};
kotlin
when expression
val App = FC {
// ...
div {
// ...
when (gameState) {
GameState.Start -> StartScreen()
GameState.Playing -> PlayingScreen()
GameState.Win -> WinScreen()
GameState.Dead -> EndScreen()
}
}
}
– Both languages support object destructuring
– Within blocks and in lambda parameters
– However, Kotlin’s is limited
– Supported via componentN methods
– Fixed order to properties extracted
– Data classes do this automatically
destructuring
typescript > kotlin
const {value, color} = brick;
const {value, location} = brick;
Arbitrary properties extracted
export const Brick: FC<Props> = ({index}) => {
}
Destructuring on parameters
const [first, ...remaining] = bricks;
Array destructuring
conclusion
they’re both very good
but in different ways
Community
Coroutines
JSX vs React DSL
Multiplatform
Advanced Type System
Extensions
Interop with JS
Expressions
Destructuring
Standard Library
Tooling
Functions
favour stable engineering
Questions?
TypeScript Vs. KotlinJS

More Related Content

Similar to TypeScript Vs. KotlinJS

Novidades do c# 7 e 8
Novidades do c# 7 e 8Novidades do c# 7 e 8
Novidades do c# 7 e 8
Giovanni Bassi
 
Fall in love with Kotlin
Fall in love with KotlinFall in love with Kotlin
Fall in love with Kotlin
Hari Vignesh Jayapalan
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
Matthew Clarke
 
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveWriting Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
André Oriani
 
Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
Syed Awais Mazhar Bukhari
 
Compose in Theory
Compose in TheoryCompose in Theory
Compose in Theory
Garth Gilmour
 
Mini-Training: TypeScript
Mini-Training: TypeScriptMini-Training: TypeScript
Mini-Training: TypeScript
Betclic Everest Group Tech Team
 
GDG Kuwait - Modern android development
GDG Kuwait - Modern android developmentGDG Kuwait - Modern android development
GDG Kuwait - Modern android development
GDGKuwaitGoogleDevel
 
Polyglot
PolyglotPolyglot
Polyglot
Rory Preddy
 
Kotlin for android 2019
Kotlin for android 2019Kotlin for android 2019
Kotlin for android 2019
Shady Selim
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
Maarten Balliauw
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
tdc-globalcode
 
Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)
Vitaly Baum
 
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
Igalia
 
Tml for Objective C
Tml for Objective CTml for Objective C
Tml for Objective C
Michael Berkovich
 
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
DILo Surabaya
 
Davide Cerbo - Kotlin loves React - Codemotion Milan 2018
Davide Cerbo - Kotlin loves React - Codemotion Milan 2018Davide Cerbo - Kotlin loves React - Codemotion Milan 2018
Davide Cerbo - Kotlin loves React - Codemotion Milan 2018
Codemotion
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
Sang Don Kim
 
Next Gen Data Modeling in the Open Data Platform With Doron Porat and Liran Y...
Next Gen Data Modeling in the Open Data Platform With Doron Porat and Liran Y...Next Gen Data Modeling in the Open Data Platform With Doron Porat and Liran Y...
Next Gen Data Modeling in the Open Data Platform With Doron Porat and Liran Y...
HostedbyConfluent
 
Oh the compilers you'll build
Oh the compilers you'll buildOh the compilers you'll build
Oh the compilers you'll build
Mark Stoodley
 

Similar to TypeScript Vs. KotlinJS (20)

Novidades do c# 7 e 8
Novidades do c# 7 e 8Novidades do c# 7 e 8
Novidades do c# 7 e 8
 
Fall in love with Kotlin
Fall in love with KotlinFall in love with Kotlin
Fall in love with Kotlin
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
 
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveWriting Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
 
Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
 
Compose in Theory
Compose in TheoryCompose in Theory
Compose in Theory
 
Mini-Training: TypeScript
Mini-Training: TypeScriptMini-Training: TypeScript
Mini-Training: TypeScript
 
GDG Kuwait - Modern android development
GDG Kuwait - Modern android developmentGDG Kuwait - Modern android development
GDG Kuwait - Modern android development
 
Polyglot
PolyglotPolyglot
Polyglot
 
Kotlin for android 2019
Kotlin for android 2019Kotlin for android 2019
Kotlin for android 2019
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
 
Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)
 
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
 
Tml for Objective C
Tml for Objective CTml for Objective C
Tml for Objective C
 
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
 
Davide Cerbo - Kotlin loves React - Codemotion Milan 2018
Davide Cerbo - Kotlin loves React - Codemotion Milan 2018Davide Cerbo - Kotlin loves React - Codemotion Milan 2018
Davide Cerbo - Kotlin loves React - Codemotion Milan 2018
 
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
[Td 2015] what is new in visual c++ 2015 and future directions(ulzii luvsanba...
 
Next Gen Data Modeling in the Open Data Platform With Doron Porat and Liran Y...
Next Gen Data Modeling in the Open Data Platform With Doron Porat and Liran Y...Next Gen Data Modeling in the Open Data Platform With Doron Porat and Liran Y...
Next Gen Data Modeling in the Open Data Platform With Doron Porat and Liran Y...
 
Oh the compilers you'll build
Oh the compilers you'll buildOh the compilers you'll build
Oh the compilers you'll build
 

More from Garth Gilmour

Shut Up And Eat Your Veg
Shut Up And Eat Your VegShut Up And Eat Your Veg
Shut Up And Eat Your Veg
Garth Gilmour
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
Garth Gilmour
 
The Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITThe Heat Death Of Enterprise IT
The Heat Death Of Enterprise IT
Garth Gilmour
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
Garth Gilmour
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour
 
Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)
Garth Gilmour
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Garth Gilmour
 
Is Software Engineering A Profession?
Is Software Engineering A Profession?Is Software Engineering A Profession?
Is Software Engineering A Profession?
Garth Gilmour
 
Social Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlySocial Distancing is not Behaving Distantly
Social Distancing is not Behaving Distantly
Garth Gilmour
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
Garth Gilmour
 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into Kotlin
Garth Gilmour
 
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Garth Gilmour
 
The Three Horse Race
The Three Horse RaceThe Three Horse Race
The Three Horse Race
Garth Gilmour
 
The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming
Garth Gilmour
 
BelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopBelTech 2019 Presenters Workshop
BelTech 2019 Presenters Workshop
Garth Gilmour
 
Kotlin The Whole Damn Family
Kotlin The Whole Damn FamilyKotlin The Whole Damn Family
Kotlin The Whole Damn Family
Garth Gilmour
 
The Philosophy of DDD
The Philosophy of DDDThe Philosophy of DDD
The Philosophy of DDD
Garth Gilmour
 
10 Big Ideas from Industry
10 Big Ideas from Industry10 Big Ideas from Industry
10 Big Ideas from Industry
Garth Gilmour
 
'Full Stack Kotlin' Workshop at KotlinConf
'Full Stack Kotlin' Workshop at KotlinConf'Full Stack Kotlin' Workshop at KotlinConf
'Full Stack Kotlin' Workshop at KotlinConf
Garth Gilmour
 
FFS The Browser and Everything In It Is Wrong - We've Ruined Software Enginee...
FFS The Browser and Everything In It Is Wrong - We've Ruined Software Enginee...FFS The Browser and Everything In It Is Wrong - We've Ruined Software Enginee...
FFS The Browser and Everything In It Is Wrong - We've Ruined Software Enginee...
Garth Gilmour
 

More from Garth Gilmour (20)

Shut Up And Eat Your Veg
Shut Up And Eat Your VegShut Up And Eat Your Veg
Shut Up And Eat Your Veg
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
The Heat Death Of Enterprise IT
The Heat Death Of Enterprise ITThe Heat Death Of Enterprise IT
The Heat Death Of Enterprise IT
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)Generics On The JVM (What you don't know will hurt you)
Generics On The JVM (What you don't know will hurt you)
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
 
Is Software Engineering A Profession?
Is Software Engineering A Profession?Is Software Engineering A Profession?
Is Software Engineering A Profession?
 
Social Distancing is not Behaving Distantly
Social Distancing is not Behaving DistantlySocial Distancing is not Behaving Distantly
Social Distancing is not Behaving Distantly
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into Kotlin
 
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
Simpler and Safer Java Types (via the Vavr and Lambda Libraries)
 
The Three Horse Race
The Three Horse RaceThe Three Horse Race
The Three Horse Race
 
The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming The Bestiary of Pure Functional Programming
The Bestiary of Pure Functional Programming
 
BelTech 2019 Presenters Workshop
BelTech 2019 Presenters WorkshopBelTech 2019 Presenters Workshop
BelTech 2019 Presenters Workshop
 
Kotlin The Whole Damn Family
Kotlin The Whole Damn FamilyKotlin The Whole Damn Family
Kotlin The Whole Damn Family
 
The Philosophy of DDD
The Philosophy of DDDThe Philosophy of DDD
The Philosophy of DDD
 
10 Big Ideas from Industry
10 Big Ideas from Industry10 Big Ideas from Industry
10 Big Ideas from Industry
 
'Full Stack Kotlin' Workshop at KotlinConf
'Full Stack Kotlin' Workshop at KotlinConf'Full Stack Kotlin' Workshop at KotlinConf
'Full Stack Kotlin' Workshop at KotlinConf
 
FFS The Browser and Everything In It Is Wrong - We've Ruined Software Enginee...
FFS The Browser and Everything In It Is Wrong - We've Ruined Software Enginee...FFS The Browser and Everything In It Is Wrong - We've Ruined Software Enginee...
FFS The Browser and Everything In It Is Wrong - We've Ruined Software Enginee...
 

Recently uploaded

Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Envertis Software Solutions
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
aymanquadri279
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 

Recently uploaded (20)

Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 

TypeScript Vs. KotlinJS

  • 1.
  • 2. © Instil Software 2020 TypeScript vs KotlinJS should you make the switch?
  • 5. – TS brings types and compilation to JS – Improves upon the existing strengths of JS – Makes us more productive and happy – Leverages existing JS frameworks – Interop with JS is a design goal we love typescript it solves real problems for us
  • 6. – Kotlin improves upon Java in many ways – Adds null safety, DSLs, coroutines etc... – Makes us more productive and happy – Leverages existing JVM frameworks – But interop with Java is a design goal we love kotlin it solves real problems for us
  • 7.
  • 9. experiment: is kotlinjs worth it? – We are not using KotlinJS in production – The code written has been for labs, workshops and talks – Built several apps both TypeScript and KotlinJS – Go beyond “hello world” – Incorporate common JS libraries – Compare the experience – Tooling – Language features – Community what problem does it solve?
  • 11. – Template project from IntelliJ – Grade project using Kotlin DSL – Easily integrate NPM packages creating new project the wizard
  • 12.
  • 13.
  • 14. multiplatform libraries COMMON KOTLIN KOTLIN ANDROID KOTLIN JS KOTLIN NATIVE KOTLIN JVM NATIVE ARTEFACT JS BUNDLE JAR
  • 16. configuring the kotlin gradle dsl plugins{ kotlin("js")version"1.6.21" kotlin("plugin.serialization")version"1.6.21" } group="org.example" version="1.0-SNAPSHOT" valktorVersion="2.0.2" repositories{ mavenCentral()} dependencies{ ...}
  • 17. configuring the kotlin gradle dsl kotlin{ js(LEGACY){ binaries.executable() browser{ commonWebpackConfig{ cssSupport.enabled=true } } } } There is a new IR compiler
  • 18. tasks in the kotlin gradle dsl
  • 19. add multiplatform and kotlinjs packages kotlinjs, multiplatform and npm dependencies { implementation("org.jetbrains.kotlin-wrappers:kotlin-react:17.0.2-pre.290-kotlin-1.6.10") implementation("org.jetbrains.kotlin-wrappers:kotlin-react-dom:17.0.2-pre.290-kotlin-1.6.10") implementation("org.jetbrains.kotlin-wrappers:kotlin-react-router-dom:6.3.0-pre.340-compat") implementation("org.jetbrains.kotlin-wrappers:kotlin-react-css:17.0.2-pre.290-kotlin-1.6.10") implementation(npm("bootstrap", "4.6.0")) implementation(npm("jquery", "1.9.1- 3")) implementation(npm("popper.js", "^1.16.1")) }
  • 20. what’s the code like standard main function funmain() { valcontainer= document.createElement("div") document.body!!.appendChild(container) valapp=App.create() render(app,container) }
  • 21. what’s the code like easy access to browser apis funmain() { valcontainer= document.createElement("div") document.body!!.appendChild(container) valapp=App.create() render(app,container) }
  • 22. what’s the code like easy access to react library valApp=FC<Props>("Application"){ BrowserRouter{ div{ p{ Link{ to="/hello”+"SimpleComponent”}} } div{ Routes{ Route{ // … } } } }
  • 24. its popularity continues to grow rising star on language rankings … 18 Kotlin … https://redmonk.com/sogrady/2021/03/01 /language-rankings-1-21/ The RedMonk Programming Language Rankings: January 2021
  • 25. its popularity continues to grow rising star on language rankings https://insights.stackoverflow.com/survey/2020 Stack Overflow Developer Survey 2020 Most Used Language 13th Kotlin 1st JavaScript 8th TypeScript
  • 26. its popularity continues to grow loved by its users https://insights.stackoverflow.com/survey/2020 Stack Overflow Developer Survey 2020 Most Loved Language 2nd TypeScript 4th Kotlin 10th JavaScript 1st Rust
  • 27. TS is the largest alternative to JS https://2021.stateofjs.com/en-US/
  • 28. – TypeScript is more popular than KotlinJS – As a superset of JS, reusing knowledge and assets is easier – And the transition for JS developers to TS is easier – TypeScript is well established in the JavaScript world – Many libraries include TypeScript definitions – DefinitelyTyped contains many more community, maturity and support typescript > kotlin
  • 30. – Only a few first class wrappers provided – It is easy to add NPM packages yourself – But how easy is it to consume that code in Kotlin? importing npm js packages gradle dsl dependencies { . . . implementation(npm("react-three-fiber", "4.2.20")) implementation(npm("react-use-gesture", "7.0.15")) implementation(npm("three", "0.119.1")) }
  • 31. really easy external declarations @file:JsModule("react-three-fiber") @file:JsNonModule ... external val Canvas: RClass<RProps> external fun extend(objects: Any) external fun useFrame(callback: (dynamic, Double) -> Unit) external fun useThree(): dynamic external interface PointerEvent { val uv: Vector2 } Specify the NPM package Define any items you wish to use
  • 32. – Converts TypeScript d.ts files to Kotlin external declarations – Still experimental – At time of writing, on hold until IR compiler stabilises dukat automatic generation https://kotlinlang.org/docs/js-external-declarations-with-dukat.html
  • 33. – Command line tool – Installable in isolation via npm – Simply point to a .d.ts file and it will do the rest dukat usage $ dukat index.d.ts index.module_my-library.kt $ npm install dukat
  • 34. dukat export function getString(): string; export function setString(input: string): void; external fun getString(): String external fun setString(input: String)
  • 35. – Integrated into Gradle – Generates definitions for configured packages dukat usage Dukat tasks ----------- generateExternals generateExternalsIntegrated
  • 36. dukat export interface BasicInterface { readonly field1: number; method1(): boolean; } export function buildInterface(): BasicInterface; export type ReadOnlyBasicInterface = Readonly<BasicInterface>; external interface BasicInterface { var field1: Number fun method1(): Boolean } external fun buildInterface(): BasicInterface typealias ReadOnlyBasicInterface = Readonly<BasicInterface>
  • 37. – It’s a good help but has issues – Limited by differences in the languages – Not a seamless workflow – This situation may improve as the tool and Kotlin evolves not a silver bullet square peg and a round hole
  • 38. – KotlinJS supports a dynamic type – You can use it in place of any type – Assign it a value of any type – Access and use members with any name – Basically switches off type checking – This can be used to quickly patch over APIs dynamic get out of jail type external fun useFrame(callback: (dynamic, Double) -> Unit)
  • 39. – Object literals are common in JavaScript – KotlinJS has a helper function to create objects – This is strongly typed (inferred) but requires fields to be var jso object literals in kotlinjs Block(jso { position = brick.location.toVector3() color = brick.color })
  • 40. – We can embed JavaScript directly with the js function – The code can even use Kotlin variables – Must be a compile time constant – Cannot be a runtime evaluated expression js embedding javascript private fun getToken(): String? { val tokenKey = TokenKey return js(""" localStorage.getItem(tokenKey) """) }
  • 41. – As a superset, TypeScript has to win this one – The type system is geared to support JavaScript – Lots of libraries already provide TypeScript definition files – However, writing external declaration in KotlinJS is easy – Dukat exists but has fundamental limitations – You may have to write custom translation code on top interop with javascript typescript > kotlinjs
  • 43. JSX IN TYPESCRIPT JSX embeds markup inside JS / TS code export const TaskItem: FC<Props> = (props) => <tr key={props.taskIndex}> <td>{props.task.text}</td> <td> <span onClick={props.onToggle}> {pickIcon(props.task.done)} </span> </td> </tr>
  • 44. val TaskItem= functionalComponent<TaskItemProps>("TaskItem"){ props -> tr{ td { +props.task.text } td { span { +pickIcon(props.task.done) } attrs { onClickFunction= { props.onToggle() } } } } } fun RBuilder.TaskItem(task: Task) = child(TaskItem) { attrs { this.task = task } } REACT DSL IN KOTLIN In Kotlin a DSL provides equivalent functionality
  • 45. kotlin DSL’s are very cool a major advantage
  • 46. val TaskItem= functionalComponent<TaskItemProps>("TaskItem"){ props -> tr{ td { +props.task.text } td { span { +pickIcon(props.task.done) } attrs { onClickFunction= { props.onToggle() } } } } } fun RBuilder.TaskItem(task: Task) = child(TaskItem) { attrs { this.task = task } } REACT DSL IN KOTLIN JSX is clearly a lot simpler / shorter
  • 47. Then they rewrote it (without telling anyone)
  • 48.
  • 49. val TaskItem=FC<TaskItemProps>("TaskItem"){props-> tr{ td{ +props.task.text} td{ onClick={ props.onToggle()} span{ +pickIcon(props.task.done) } } } } REACT DSL IN KOTLIN
  • 50. val TaskItem=FC<TaskItemProps>("TaskItem"){props-> tr{ td{ +props.task.text} td{ onClick={ props.onToggle()} span{ +pickIcon(props.task.done) } } } } REACT DSL IN KOTLIN Builder functions not required Many attributes are cleaner attrs section is gone
  • 51. The typing is ... imperfect
  • 52. interface InputHTMLAttributes<T> extends HTMLAttributes<T> { max?: number | string; min?: number | string; value?: string | ReadonlyArray<string> | number; ... } Type union type PropsWithChildren<P> = P & { children?: ReactNode }; Type intersection
  • 53. // Type exports erased! external fun interfaceUnionInput(input: First) external fun interfaceUnionInput(input: Second) external fun interfaceUnionOutput(): dynamic /* First | Second */ export type InterfaceUnion = First | Second; export function interfaceUnionInput(input: InterfaceUnion): void; export function interfaceUnionOutput(): InterfaceUnion; Kotlin supports proper overloads Not supported on the return type
  • 54. external fun interfaceIntersectionInput(input: First /* First & Second */) external fun interfaceIntersectionOutput(): First /* First & Second */ export type InterfaceIntersection = First & Second; export function interfaceIntersectionInput(input: InterfaceIntersection): void; export function interfaceIntersectionOutput(): InterfaceIntersection; Intersection dropped
  • 55. mapped and conditional types even more power in typescript type Readonly<T> = { readonly [P in keyof T]: T[P]; }; type PromiseType<T extends Promise<any>> = T extends Promise<infer U> ? U : never; Type conditional
  • 56. The languages are simply not fully compatible
  • 57. manual workarounds useEffect function useEffect( effect: EffectCallback, deps?: DependencyList ): void; type EffectCallback = () => (void | Destructor); type Destructor = () => void;
  • 58. useEffect union return workaround fun useEffect( dependencies: RDependenciesList? = null, effect: () -> Unit ) { // ... } fun useEffectWithCleanup( dependencies: RDependenciesList? = null, effect: () -> Rcleanup ) { // ... }
  • 59. useEffect or other patterns useEffect { } useEffect(dep1, dep2) { } useEffectOnce { } useEffectOnce { cleanup { // Clean up logic goes here } }
  • 60. – Kotlin’s DSL support is a powerful general purpose tool – But JSX is a single purpose solution that suits React better – TypeScript’s advanced type system is very powerful – Union, intersection and mapped types bring sanity to JS – Kotlin types (unsurprisingly) sit awkwardly on top of JS jsx vs dsl typescript > kotlin
  • 61. async await vs coroutines Round 4
  • 62. asynchronous programming – Async await is a good async solution in JS & TS – Engineered so it interops with Promises – Succinct promises and async/await async function loadMap(url: string): Promise<void> { const response = await fetch(url); const map = await response.text(); // ... }
  • 63. coroutines – Kotlin’s more general coroutines are better – Works with other patterns than simply async – In KotlinJS, it works easily with Promises kotlin > typescript suspend fun loadMap(url: String) { val response = window.fetch(url).await() val map = response.text().await() // ... }
  • 64. coroutines – Coroutines are more general and powerful – They can be used with other patterns too – With suspend functions we don’t need to “await” kotlin > typescript suspend fun loadMap(url: String) { val map = client.get<String>(url) // ... } Ktor Client
  • 65. coroutines – Coroutines can be applied to other patterns too kotlin > typescript fun infinite() = sequence { var count = 0 while (true) { yield(count++) } }
  • 67. – Kotlin doesn’t have the ternary, but has more – when for basic pattern matching – if and when are expressions – Unit instead of void – Expression bodied functions – This creates more symmetry in code expressions kotlin > typescript
  • 68. typescript chained ternaries const App: FC = () => { // ... return ( <div> // ... {gameState === GameState.Start ? <StartScreen/> : gameState === GameState.Playing ? <PlayingGame/> : gameState === GameState.Dead ? <DeathScreen/> : gameState === GameState.Win ? <WinScreen/> : null} </div> ); };
  • 69. kotlin when expression val App = FC { // ... div { // ... when (gameState) { GameState.Start -> StartScreen() GameState.Playing -> PlayingScreen() GameState.Win -> WinScreen() GameState.Dead -> EndScreen() } } }
  • 70. – Both languages support object destructuring – Within blocks and in lambda parameters – However, Kotlin’s is limited – Supported via componentN methods – Fixed order to properties extracted – Data classes do this automatically destructuring typescript > kotlin
  • 71. const {value, color} = brick; const {value, location} = brick; Arbitrary properties extracted export const Brick: FC<Props> = ({index}) => { } Destructuring on parameters const [first, ...remaining] = bricks; Array destructuring
  • 73. they’re both very good but in different ways
  • 74. Community Coroutines JSX vs React DSL Multiplatform Advanced Type System Extensions Interop with JS Expressions Destructuring Standard Library Tooling Functions

Editor's Notes

  1. Lots to love in JavaScript – ubiquitous, popularity/community, succinct syntax, object literals, destructuring But it’s dynamic typing. I’m a fan of static typing
  2. Lots to love in JavaScript – ubiquitous, popularity/community, succinct syntax, object literals, destructuring But it’s dynamic typing. I’m a fan of static typing
  3. Emphasize how good it is you can start writing code
  4. Emphasize how good it is you can start writing code
  5. Emphasize how good it is you can start writing code
  6. Ask the question – top spot?
  7. Ask the question – top spot?
  8. TypeScript is more capable when it comes to type programming Not easy to integrate customisations (which are common) If kotlin evolves to support more TS features, less customisation will be necessary
  9. More libraries may come out
  10. We can trim it down but grouping closing braces We could also group params but So first off, THIS IS PRETTY COOL that we can do this
  11. We can trim it down but grouping closing braces We could also group params but So first off, THIS IS PRETTY COOL that we can do this
  12. Cumberbatch for cumbersome
  13. Cumberbatch for cumbersome
  14. Union done as overloads – good! Output simply dynamic - bad
  15. It’s not to say you can achieve the desired behaviour