SlideShare una empresa de Scribd logo
1 de 31
Mixing
Scala and Kotlin
March 2021
Alexey Soshin
Solutions Architect
Agenda
● What is Depop
● Why?!
● Collections
● Nullability
● Functions
● Coroutines
Depop
Building the most diverse, progressive
Home of Fashion.
● Fashion marketplace app for the next generation
to buy, sell and discover unique fashion.
● Community of like minded creatives, young
entrepreneurs and sustainable enthusiasts who
are transforming the fashion industry.
● Globally, over 26 million users on the platform in
147 countries, and 90% of our active users are
under the age of 26, or Gen Z.
● As an app based platform, Depop combines the
familiarity of social media with the mechanics of
a resale marketplace.
● Our Mission is to Empower our community to
create a new sustainable and equitable fashion
system.
Motivation
Scala was there first
● Scala first appeared around 2004
● Kotlin - 2011, out of Beta in 2016
The Dinosaur in the Room
Scala engineers are rare
Scala is F[_] hard
Mobile Developers ❤️ Kotlin
● Kotlin is the main language
on Android
● Conceptually closer to Swift
than Scala
● Great for Backend For
Frontend approach, where
Mobile engineers control the
API layer
Map[String, String] or
Map<String, String>?
def doSomething(properties: Map[String, List[String]])
fun doSomething(properties: Map<String, List<String>>)
Type mismatch:
inferred type is kotlin.collections.Map<String, kotlin.collections.List<String>>
but scala.collection.immutable.Map<String!,
scala.collection.immutable.List<String!>!>! was expected
🤔
😱
Collections
Collections
def doSomething(m: Map[String, List[String]])
doSomething(mapOf("hello" to listOf("world")))
import scala.collection.JavaConverters._
def doSomething(m: java.util.Map[String,
java.util.List[String]])
Collections
def doSomething(m: java.util.Map[String,
java.util.List[String]]) = {
val a: mutable.Map[String, util.List[String]] =
m.asScala
val b: collection.Map[String, List[String]] =
a.mapValues(l => l.asScala.toList)
doSomething(b.toMap)
}
def doSomething(m: Map[String, List[String]])
Scala Option vs Kotlin
nullability
def doSomething(value: Option[String] = None)
fun doSomething(value: String?)
🤔
Nullability
Type mismatch:
Required: Option<String!>!
Found: String?
inline fun <reified T> none() = Option.empty<T>()
inline fun <reified T> some(t: T) = Option.apply(t)
if (value == null) none() else some(value)
private fun Any?.asOption() = if (this == null) none() else some(this)
Nullability
When a Function is not
a Function
def executeBlock(block: () => Unit) = {
println("I'm going to execute it!")
block()
}
fun executeBlock(block: () -> Unit) {
println("I'm going to execute it!")
block()
}
Functions
=?
MainKt.executeBlock(() => println("Hello from Scala"))
Error: type mismatch;
found : Unit (in scala)
required: Unit (in kotlin)
MainKt.executeBlock(() => println("hello"))
Functions
def executeBlock(block: () => Unit) = {
println("I'm going to execute it!")
block()
}
≠
fun executeBlock(block: () -> Unit) {
println("I'm going to execute it!")
block()
}
kotlin.jvm.functions.Function0 scala.Function0
Functions
def executeBlock(block: () => Int): Int = {
println("I'm going to execute it!")
block()
1
}
=?
fun executeBlock(block: () -> Int): Int {
println("I'm going to execute it!")
block()
return 1
}
kotlin.jvm.functions.Function0 scala.Function0
≠
Functions
MainKt.executeBlock(() => 1)
ScalaObject.executeBlock {
println("Hello from Kotlin")
1
}
👍
👍
Functions
Coroutines
class AsyncKotlinClass : CoroutineScope {
override val coroutineContext = Dispatchers.Default
fun getCatAsync(name: String) = async {
Cat(name)
}
suspend fun getCat(name: String): Cat {
delay(100)
return Cat(name)
}
}
Coroutines
val asyncKotlinClass = new AsyncKotlinClass()
val res = asyncKotlinClass.getCatAsync("Fluffy")
val cat = res.await()
Error: not enough arguments for method await:
(x$1: kotlin.coroutines.Continuation[_ >: Cat])Object.
Unspecified value parameter x$1.
val cat = res.await()
Coroutines
val asyncKotlinClass = new AsyncKotlinClass()
val cat = asyncKotlinClass.getCat("Fluffy")
Error: not enough arguments for method getCat:
(x$1: String, x$2: kotlin.coroutines.Continuation[_ >: Cat])Object.
Unspecified value parameter x$2.
val cat = asyncKotlinClass.getCat("Fluffy")
😱
Coroutines
Coroutines
import kotlinx.coroutines.future.*
fun getCatAsync(name: String) =
async {
Cat(name)
}.asCompletableFuture()
import
scala.compat.java8.FutureConverters._
val asyncKotlinClass = new
AsyncKotlinClass()
val res =
asyncKotlinClass.getCatAsync("Fluffy")
val cat = toScala(res)
Coroutines
Summary
● Reasons to adopt Kotlin in a Scala company:
○ Easier to adopt
○ Mobile Developers love it
● Reasons to keep using Scala
○ Very powerful language
○ Lots of code already written in it
● If you need to mix Scala and Kotlin
○ Easier to call Kotlin from Scala than Scala from
Kotlin
We’re Hiring!
Our Blog: https://engineering.depop.com
Tech careers:
https://boards.greenhouse.io/depop
Stay connected:
https://alexey-soshin.medium.com/
https://twitter.com/alexey_soshin
https://www.udemy.com/user/alexey-soshin/
THANK YOU

Más contenido relacionado

La actualidad más candente

TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Simplilearn
 
今から始める Lens/Prism
今から始める Lens/Prism今から始める Lens/Prism
今から始める Lens/PrismNaoki Aoyama
 
純粋関数型アルゴリズム入門
純粋関数型アルゴリズム入門純粋関数型アルゴリズム入門
純粋関数型アルゴリズム入門Kimikazu Kato
 
Ansible specでテストをする話
Ansible specでテストをする話Ansible specでテストをする話
Ansible specでテストをする話KeijiUehata1
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Scott Wlaschin
 
C++でテスト駆動開発
C++でテスト駆動開発C++でテスト駆動開発
C++でテスト駆動開発Akineko Shimizu
 
Constexpr 中3女子テクニック
Constexpr 中3女子テクニックConstexpr 中3女子テクニック
Constexpr 中3女子テクニックGenya Murakami
 
Laravelでfacadeを使わない開発
Laravelでfacadeを使わない開発Laravelでfacadeを使わない開発
Laravelでfacadeを使わない開発Kenjiro Kubota
 
CEDEC 2018 最速のC#の書き方 - C#大統一理論へ向けて性能的課題を払拭する
CEDEC 2018 最速のC#の書き方 - C#大統一理論へ向けて性能的課題を払拭するCEDEC 2018 最速のC#の書き方 - C#大統一理論へ向けて性能的課題を払拭する
CEDEC 2018 最速のC#の書き方 - C#大統一理論へ向けて性能的課題を払拭するYoshifumi Kawai
 
Tensor flow usergroup 2016 (公開版)
Tensor flow usergroup 2016 (公開版)Tensor flow usergroup 2016 (公開版)
Tensor flow usergroup 2016 (公開版)Hiroki Nakahara
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming LanguageJaeju Kim
 
Scalaで型クラス入門
Scalaで型クラス入門Scalaで型クラス入門
Scalaで型クラス入門Makoto Fukuhara
 

La actualidad más candente (20)

Function lecture
Function lectureFunction lecture
Function lecture
 
Java 11 to 17 : What's new !?
Java 11 to 17 : What's new !?Java 11 to 17 : What's new !?
Java 11 to 17 : What's new !?
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
C#.NET
C#.NETC#.NET
C#.NET
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022
 
今から始める Lens/Prism
今から始める Lens/Prism今から始める Lens/Prism
今から始める Lens/Prism
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
純粋関数型アルゴリズム入門
純粋関数型アルゴリズム入門純粋関数型アルゴリズム入門
純粋関数型アルゴリズム入門
 
Ansible specでテストをする話
Ansible specでテストをする話Ansible specでテストをする話
Ansible specでテストをする話
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
 
Java string handling
Java string handlingJava string handling
Java string handling
 
C++でテスト駆動開発
C++でテスト駆動開発C++でテスト駆動開発
C++でテスト駆動開発
 
Constexpr 中3女子テクニック
Constexpr 中3女子テクニックConstexpr 中3女子テクニック
Constexpr 中3女子テクニック
 
Laravelでfacadeを使わない開発
Laravelでfacadeを使わない開発Laravelでfacadeを使わない開発
Laravelでfacadeを使わない開発
 
CEDEC 2018 最速のC#の書き方 - C#大統一理論へ向けて性能的課題を払拭する
CEDEC 2018 最速のC#の書き方 - C#大統一理論へ向けて性能的課題を払拭するCEDEC 2018 最速のC#の書き方 - C#大統一理論へ向けて性能的課題を払拭する
CEDEC 2018 最速のC#の書き方 - C#大統一理論へ向けて性能的課題を払拭する
 
Tensor flow usergroup 2016 (公開版)
Tensor flow usergroup 2016 (公開版)Tensor flow usergroup 2016 (公開版)
Tensor flow usergroup 2016 (公開版)
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming Language
 
Spring tools4
Spring tools4Spring tools4
Spring tools4
 
Scalaで型クラス入門
Scalaで型クラス入門Scalaで型クラス入門
Scalaで型クラス入門
 

Similar a Mixing Scala and Kotlin

Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?intelliyole
 
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
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with AndroidKurt Renzo Acosta
 
Anko & Karamba in Kotlin by Bapusaheb Patil
Anko & Karamba in Kotlin by Bapusaheb PatilAnko & Karamba in Kotlin by Bapusaheb Patil
Anko & Karamba in Kotlin by Bapusaheb PatilBapusaheb Patil
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisRuslan Shevchenko
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyTypesafe
 
Power Up Your Build - Omer van Kloeten @ Wix 2018-04
Power Up Your Build - Omer van Kloeten @ Wix 2018-04Power Up Your Build - Omer van Kloeten @ Wix 2018-04
Power Up Your Build - Omer van Kloeten @ Wix 2018-04Omer van Kloeten
 
3 little clojure functions
3 little clojure functions3 little clojure functions
3 little clojure functionsDiego Pacheco
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyManageIQ
 
Introduction to meta-programming in scala
Introduction to meta-programming in scalaIntroduction to meta-programming in scala
Introduction to meta-programming in scalaAlessandro Marrella
 
From Android NDK To AOSP
From Android NDK To AOSPFrom Android NDK To AOSP
From Android NDK To AOSPMin-Yih Hsu
 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Mohamed Nabil, MSc.
 
Monix : A Birds’ eye view
Monix : A Birds’ eye viewMonix : A Birds’ eye view
Monix : A Birds’ eye viewKnoldus Inc.
 
SpringOne Platform recap 정윤진
SpringOne Platform recap 정윤진SpringOne Platform recap 정윤진
SpringOne Platform recap 정윤진VMware Tanzu Korea
 

Similar a Mixing Scala and Kotlin (20)

Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
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
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Anko & Karamba in Kotlin by Bapusaheb Patil
Anko & Karamba in Kotlin by Bapusaheb PatilAnko & Karamba in Kotlin by Bapusaheb Patil
Anko & Karamba in Kotlin by Bapusaheb Patil
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
 
Power Up Your Build - Omer van Kloeten @ Wix 2018-04
Power Up Your Build - Omer van Kloeten @ Wix 2018-04Power Up Your Build - Omer van Kloeten @ Wix 2018-04
Power Up Your Build - Omer van Kloeten @ Wix 2018-04
 
Polyglot
PolyglotPolyglot
Polyglot
 
Intro to OOP
Intro to OOPIntro to OOP
Intro to OOP
 
3 little clojure functions
3 little clojure functions3 little clojure functions
3 little clojure functions
 
Coscup
CoscupCoscup
Coscup
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
 
Introduction to meta-programming in scala
Introduction to meta-programming in scalaIntroduction to meta-programming in scala
Introduction to meta-programming in scala
 
Sync considered unethical
Sync considered unethicalSync considered unethical
Sync considered unethical
 
Introduction to Qt
Introduction to QtIntroduction to Qt
Introduction to Qt
 
From Android NDK To AOSP
From Android NDK To AOSPFrom Android NDK To AOSP
From Android NDK To AOSP
 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
 
Monix : A Birds’ eye view
Monix : A Birds’ eye viewMonix : A Birds’ eye view
Monix : A Birds’ eye view
 
SpringOne Platform recap 정윤진
SpringOne Platform recap 정윤진SpringOne Platform recap 정윤진
SpringOne Platform recap 정윤진
 

Último

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 

Último (20)

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 

Mixing Scala and Kotlin

  • 1. Mixing Scala and Kotlin March 2021 Alexey Soshin Solutions Architect
  • 2. Agenda ● What is Depop ● Why?! ● Collections ● Nullability ● Functions ● Coroutines
  • 3. Depop Building the most diverse, progressive Home of Fashion. ● Fashion marketplace app for the next generation to buy, sell and discover unique fashion. ● Community of like minded creatives, young entrepreneurs and sustainable enthusiasts who are transforming the fashion industry. ● Globally, over 26 million users on the platform in 147 countries, and 90% of our active users are under the age of 26, or Gen Z. ● As an app based platform, Depop combines the familiarity of social media with the mechanics of a resale marketplace. ● Our Mission is to Empower our community to create a new sustainable and equitable fashion system.
  • 5. Scala was there first ● Scala first appeared around 2004 ● Kotlin - 2011, out of Beta in 2016
  • 6. The Dinosaur in the Room
  • 9. Mobile Developers ❤️ Kotlin ● Kotlin is the main language on Android ● Conceptually closer to Swift than Scala ● Great for Backend For Frontend approach, where Mobile engineers control the API layer
  • 11. def doSomething(properties: Map[String, List[String]]) fun doSomething(properties: Map<String, List<String>>) Type mismatch: inferred type is kotlin.collections.Map<String, kotlin.collections.List<String>> but scala.collection.immutable.Map<String!, scala.collection.immutable.List<String!>!>! was expected 🤔 😱 Collections
  • 12. Collections def doSomething(m: Map[String, List[String]]) doSomething(mapOf("hello" to listOf("world"))) import scala.collection.JavaConverters._ def doSomething(m: java.util.Map[String, java.util.List[String]])
  • 13. Collections def doSomething(m: java.util.Map[String, java.util.List[String]]) = { val a: mutable.Map[String, util.List[String]] = m.asScala val b: collection.Map[String, List[String]] = a.mapValues(l => l.asScala.toList) doSomething(b.toMap) } def doSomething(m: Map[String, List[String]])
  • 14. Scala Option vs Kotlin nullability
  • 15. def doSomething(value: Option[String] = None) fun doSomething(value: String?) 🤔 Nullability Type mismatch: Required: Option<String!>! Found: String?
  • 16. inline fun <reified T> none() = Option.empty<T>() inline fun <reified T> some(t: T) = Option.apply(t) if (value == null) none() else some(value) private fun Any?.asOption() = if (this == null) none() else some(this) Nullability
  • 17. When a Function is not a Function
  • 18. def executeBlock(block: () => Unit) = { println("I'm going to execute it!") block() } fun executeBlock(block: () -> Unit) { println("I'm going to execute it!") block() } Functions =?
  • 19. MainKt.executeBlock(() => println("Hello from Scala")) Error: type mismatch; found : Unit (in scala) required: Unit (in kotlin) MainKt.executeBlock(() => println("hello")) Functions
  • 20. def executeBlock(block: () => Unit) = { println("I'm going to execute it!") block() } ≠ fun executeBlock(block: () -> Unit) { println("I'm going to execute it!") block() } kotlin.jvm.functions.Function0 scala.Function0 Functions
  • 21. def executeBlock(block: () => Int): Int = { println("I'm going to execute it!") block() 1 } =? fun executeBlock(block: () -> Int): Int { println("I'm going to execute it!") block() return 1 } kotlin.jvm.functions.Function0 scala.Function0 ≠ Functions
  • 22. MainKt.executeBlock(() => 1) ScalaObject.executeBlock { println("Hello from Kotlin") 1 } 👍 👍 Functions
  • 24. class AsyncKotlinClass : CoroutineScope { override val coroutineContext = Dispatchers.Default fun getCatAsync(name: String) = async { Cat(name) } suspend fun getCat(name: String): Cat { delay(100) return Cat(name) } } Coroutines
  • 25. val asyncKotlinClass = new AsyncKotlinClass() val res = asyncKotlinClass.getCatAsync("Fluffy") val cat = res.await() Error: not enough arguments for method await: (x$1: kotlin.coroutines.Continuation[_ >: Cat])Object. Unspecified value parameter x$1. val cat = res.await() Coroutines
  • 26. val asyncKotlinClass = new AsyncKotlinClass() val cat = asyncKotlinClass.getCat("Fluffy") Error: not enough arguments for method getCat: (x$1: String, x$2: kotlin.coroutines.Continuation[_ >: Cat])Object. Unspecified value parameter x$2. val cat = asyncKotlinClass.getCat("Fluffy") 😱 Coroutines
  • 28. import kotlinx.coroutines.future.* fun getCatAsync(name: String) = async { Cat(name) }.asCompletableFuture() import scala.compat.java8.FutureConverters._ val asyncKotlinClass = new AsyncKotlinClass() val res = asyncKotlinClass.getCatAsync("Fluffy") val cat = toScala(res) Coroutines
  • 29. Summary ● Reasons to adopt Kotlin in a Scala company: ○ Easier to adopt ○ Mobile Developers love it ● Reasons to keep using Scala ○ Very powerful language ○ Lots of code already written in it ● If you need to mix Scala and Kotlin ○ Easier to call Kotlin from Scala than Scala from Kotlin
  • 30. We’re Hiring! Our Blog: https://engineering.depop.com Tech careers: https://boards.greenhouse.io/depop Stay connected: https://alexey-soshin.medium.com/ https://twitter.com/alexey_soshin https://www.udemy.com/user/alexey-soshin/

Notas del editor

  1. Hi, My name is Alexey Soshin, I’m a Solutions Architect at Depop, And today we are gonna talk about mixing Scala and Kotlin
  2. So, the agenda for this evening. First shortly about Depop Then why would we even consider mixing Scala and Kotlin And then we’ll dive into different topics. So for today I want to cover collections, handling nulls, working with functions and coroutines Sounds good?
  3. Depop is a marketplace for fashion. We have about 25 million users globally, 30 million items, and more than one hundred thousand items added every day. In terms of engineering, we are about one hundred engineers at the moment, and around 200 microservices, which are mostly written in Scala. We also have a Python monolith that we’re slowly breaking down, but I won’t talk about that today.
  4. Every time I even mention this talk, people ask me: but why would you even do that?! Well, there are a few reasons.
  5. Scala came out in 2004, so it has at least 7 to 10 years of active development on top of Kotlin. So, companies have a lot of code already written in Scala, a lot of libraries, and we want to reuse that.
  6. Now, there’s a dinosaur in the room, and it’s of course Java. But scenarios where you need to mix Scala and Java or Kotlin in Java are actually well supported. Because authors of both languages knew that Java has a huge codebase, a lot of libraries, and you want to make sure that you can make good use of them. If you wanted to throw everything mankind achieved since 95 out of the window, you could try Go instead. Okay, so why not simply keep writing everything in Scala then? There are a few reasons for that.
  7. First, Scala engineers are hard to find. There is a lot of competition on the market for them. And once you hire them, you want to put them on the most difficult tasks. But not all of the tasks in your company are difficult. So, Kotlin is a good way to diversify your codebase. https://unsplash.com/photos/dxFi8Ea670E
  8. And the reason Scala engineers are hard to find is because Scala is a hard language. I have another talk where I try to convince the audience that it’s not that hard, but in general, it is. I encountered it mainly at Wix, where we were hiring a lot of graduates. And those were top graduates from top universities. But still for a lot of them functional programming in Scala was hard. It took them months to get productive. The courses in the university are mainly C, Java, Python, and all those are mostly imperative, almost procedural languages. So again, I would advocate Kotlin for the places that have a lot of juniors and struggle to onboard them well. https://unsplash.com/photos/WiKEnlt6Z3U
  9. And finally, there’s the Backend for Frontend services. Well, hopefully I convinced you now that there are some valid reasons to mix the two. The main goal is always to reuse the Scala codebase, Scala libraries that the organisation already has, in Kotlin microservice. I’m not advocating for putting Scala and Kotlin code in the same microservice. Although Now, let’s dive into the problems, I don’t like the word challenges, that you’ll be facing. https://unsplash.com/photos/Rs9ypWXB1vE
  10. So, let’s start with something that seems relatively simple. Compatibility between data structures
  11. So, if we look at those two functions, one is written in Kotlin, another is in Scala, we, as people, can argue that their input is exactly the same. But if we tried to invoke one passing the input to the other, we would get this friendly error message. And that will be a common motive in this talk. Since we’re on JVM, it may seem like every should just work. People were asking me why was I hired as a Principal Engineer to solve those kinds of issues. Should it you know, just work? No, it shouldn’t.
  12. So, that’s what we want to do. Just call a Scala method from Kotlin that receives a map of lists of strings. For that in Scala, we’ll need the help of JavaConverters, and to have another adapter function. Notice that here w use Java Map and Java List, instead of Scala’s That’s because Kotlin has built in support for them.
  13. But that’s not all. Even with JavaConverters, we can convert Java map to Scala map, but that won’t do a deeper conversion. So then we need to iterate over map values and convert each of them to a Scala list too. But this doesn’t produce the correct map yet, so we’ll need to call toMap on a map, to get the map we want. Fun!
  14. Those two have similar meanings, both indicate possible absence of value. But how can we integrate between them?
  15. So, your Kotlin function works with something that is a String or null. And Scala likes to receives those as Option. But nullable string is clearly not on Option of a string for the compiler.
  16. Kotlin extension methods to the rescue.
  17. I guess everybody here like functional programming. Functions are great. Let’s dive into that.
  18. On the left we have a higher order function definition from Kotlin And on the right we have the same definition in Scala You need to squint really hard to notice the difference But are they really equal?
  19. So, let’s try to pass Scala lambda to this Kotlin function And we get this error, saying that Scala Unit is not a Kotlin Unit Well, in the hindsight, that totally makes sense Those are two totally different classes
  20. So, we figured out that those two are definitely not the same And we could see that even earlier, if we just had looked at the classes behind the lambdas
  21. So, we figured out that those lambdas are represented by two different classes. If we change the return type of the lambda, the problem would still be the same. Right?
  22. Turns out, they are interchangable You can pass Scala lambda to Kotlin, and you can pass Kotlin block to Scala. So, in fact, Function in Kotlin and Function in Scala are interchangeable, as long as their input and output is interchangeable.
  23. I guess everybody here like functional programming. Functions are great. Let’s dive into that.
  24. Coroutines are similar to lightweight threads or fibers. So, here we have a Kotlin class with two methods One is asynchronous method, that returns a deferred result And another is a suspending method, which is like blocking, but instead of blocking a thread, it suspends the coroutine CoroutineContext is like an execution context
  25. Let’s try using the first one from Scala It even may look like it’s working, until you try to get the result Await() method has no arguments, but compiler demands that we pass it something called continuation as the first parameter. Doesn’t make any sense.
  26. Ok, let’s try to invoke second method. It should be simple. Now although we have one argument, we’re required to pass Continuation as a second parameter. Again, no luck.
  27. Trying to complete Scala future from Kotlin won’t work, because it’ll need execution context. So, you’ll be passing the gorilla and the entire jungle, when you just wanted the banana. But there’s something else that will help us. And this “something else” is weirdly enough - Java
  28. We can import coroutines/future package in Kotlin, and we’ll get a method that converts Kotlin Deferred value into CompletableFuture Now, Java CompletableFuture can be converted to Scala future. Or to any other future, for this matter.