SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere Àhnliche Inhalte

Was ist angesagt?

Apache Flink Training: DataStream API Part 1 Basic
 Apache Flink Training: DataStream API Part 1 Basic Apache Flink Training: DataStream API Part 1 Basic
Apache Flink Training: DataStream API Part 1 Basic
Flink Forward
 
Kafka Security 101 and Real-World Tips
Kafka Security 101 and Real-World Tips Kafka Security 101 and Real-World Tips
Kafka Security 101 and Real-World Tips
confluent
 

Was ist angesagt? (20)

ELK, a real case study
ELK,  a real case studyELK,  a real case study
ELK, a real case study
 
Financial Event Sourcing at Enterprise Scale
Financial Event Sourcing at Enterprise ScaleFinancial Event Sourcing at Enterprise Scale
Financial Event Sourcing at Enterprise Scale
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Qt Item Views In Depth
Qt Item Views In DepthQt Item Views In Depth
Qt Item Views In Depth
 
Kanban board!
Kanban board!Kanban board!
Kanban board!
 
Getting Started with Confluent Schema Registry
Getting Started with Confluent Schema RegistryGetting Started with Confluent Schema Registry
Getting Started with Confluent Schema Registry
 
Introduction to Qt programming
Introduction to Qt programmingIntroduction to Qt programming
Introduction to Qt programming
 
Stream All Things—Patterns of Modern Data Integration with Gwen Shapira
Stream All Things—Patterns of Modern Data Integration with Gwen ShapiraStream All Things—Patterns of Modern Data Integration with Gwen Shapira
Stream All Things—Patterns of Modern Data Integration with Gwen Shapira
 
CDC Stream Processing With Apache Flink With Timo Walther | Current 2022
CDC Stream Processing With Apache Flink With Timo Walther | Current 2022CDC Stream Processing With Apache Flink With Timo Walther | Current 2022
CDC Stream Processing With Apache Flink With Timo Walther | Current 2022
 
Apache Flink Training: DataStream API Part 1 Basic
 Apache Flink Training: DataStream API Part 1 Basic Apache Flink Training: DataStream API Part 1 Basic
Apache Flink Training: DataStream API Part 1 Basic
 
Python standard library &amp; list of important libraries
Python standard library &amp; list of important librariesPython standard library &amp; list of important libraries
Python standard library &amp; list of important libraries
 
Effective CMake
Effective CMakeEffective CMake
Effective CMake
 
Git and git workflow best practice
Git and git workflow best practiceGit and git workflow best practice
Git and git workflow best practice
 
Effective Java and Kotlin
Effective Java and KotlinEffective Java and Kotlin
Effective Java and Kotlin
 
Monitor Apache Spark 3 on Kubernetes using Metrics and Plugins
Monitor Apache Spark 3 on Kubernetes using Metrics and PluginsMonitor Apache Spark 3 on Kubernetes using Metrics and Plugins
Monitor Apache Spark 3 on Kubernetes using Metrics and Plugins
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Kafka Security 101 and Real-World Tips
Kafka Security 101 and Real-World Tips Kafka Security 101 and Real-World Tips
Kafka Security 101 and Real-World Tips
 
Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...
Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...
Time to-live: How to Perform Automatic State Cleanup in Apache Flink - Andrey...
 
Designing a complete ci cd pipeline using argo events, workflow and cd products
Designing a complete ci cd pipeline using argo events, workflow and cd productsDesigning a complete ci cd pipeline using argo events, workflow and cd products
Designing a complete ci cd pipeline using argo events, workflow and cd products
 
Spark SQL: Another 16x Faster After Tungsten: Spark Summit East talk by Brad ...
Spark SQL: Another 16x Faster After Tungsten: Spark Summit East talk by Brad ...Spark SQL: Another 16x Faster After Tungsten: Spark Summit East talk by Brad ...
Spark SQL: Another 16x Faster After Tungsten: Spark Summit East talk by Brad ...
 

Ähnlich wie Mixing Scala and Kotlin

Ähnlich wie 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 정윀진
 

KĂŒrzlich hochgeladen

Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Bert Jan Schrijver
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 

KĂŒrzlich hochgeladen (20)

%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] đŸ„ Women's Abortion Clinic in T...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 

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/

Hinweis der Redaktion

  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.