SlideShare a Scribd company logo
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

More Related Content

PDF
Basic Java Programming
ODP
Unit testing with Qt test
PDF
GoらしいAPIを求める旅路 (Go Conference 2018 Spring)
PDF
jenkinsで遊ぶ
PDF
Microservices with Java, Spring Boot and Spring Cloud
PDF
AWS + Windows(C#)で構築する.NET最先端技術によるハイパフォーマンスウェブアプリケーション開発実践
PPTX
Continuous integration using atlassian bamboo
PDF
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요
Basic Java Programming
Unit testing with Qt test
GoらしいAPIを求める旅路 (Go Conference 2018 Spring)
jenkinsで遊ぶ
Microservices with Java, Spring Boot and Spring Cloud
AWS + Windows(C#)で構築する.NET最先端技術によるハイパフォーマンスウェブアプリケーション開発実践
Continuous integration using atlassian bamboo
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요

What's hot (20)

PPTX
世界一わかりやすいClean Architecture release-preview
PDF
MySQLアンチパターン
PDF
Development myshoes and Provide Cycloud-hosted runner -- GitHub Actions with ...
PDF
Quarkus - a next-generation Kubernetes Native Java framework
PDF
Linux cgroups and namespaces
PDF
Rediscovering Spring with Spring Boot(1)
PDF
Event storming
PPTX
Inter Process Communication (IPC) in Android
PPTX
Introduction to Java
PDF
例外設計における大罪
PDF
QualityとDeliveryを両立させるために僕らがやったこと
PPTX
GitLabを16万8千光年ワープさせた話(改)
PPTX
Introduce Docker
PDF
Virtual machine and javascript engine
PDF
Event driven autoscaling with keda
PPTX
Steering the Course with Helm
PDF
Qt Internationalization
 
PDF
Summary of Scrum Guide
PPTX
GOTO Berlin - Battle of the Circuit Breakers: Resilience4J vs Istio
PDF
Clean architecture
世界一わかりやすいClean Architecture release-preview
MySQLアンチパターン
Development myshoes and Provide Cycloud-hosted runner -- GitHub Actions with ...
Quarkus - a next-generation Kubernetes Native Java framework
Linux cgroups and namespaces
Rediscovering Spring with Spring Boot(1)
Event storming
Inter Process Communication (IPC) in Android
Introduction to Java
例外設計における大罪
QualityとDeliveryを両立させるために僕らがやったこと
GitLabを16万8千光年ワープさせた話(改)
Introduce Docker
Virtual machine and javascript engine
Event driven autoscaling with keda
Steering the Course with Helm
Qt Internationalization
 
Summary of Scrum Guide
GOTO Berlin - Battle of the Circuit Breakers: Resilience4J vs Istio
Clean architecture
Ad

Similar to Mixing Scala and Kotlin (20)

PDF
Kotlin: Why Do You Care?
PDF
The things we don't see – stories of Software, Scala and Akka
PPTX
Building Mobile Apps with Android
PDF
Anko & Karamba in Kotlin by Bapusaheb Patil
PDF
Why scala is not my ideal language and what I can do with this
PPTX
ScalaDays 2013 Keynote Speech by Martin Odersky
PPTX
Power Up Your Build - Omer van Kloeten @ Wix 2018-04
PPTX
Polyglot
PDF
Intro to OOP
PDF
3 little clojure functions
PDF
Coscup
PPTX
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
PDF
Introduction to meta-programming in scala
PDF
Sync considered unethical
PPTX
Introduction to Qt
PDF
From Android NDK To AOSP
PDF
Kotlin for Android Developers - 1
PDF
Koin Quickstart
PDF
Monix : A Birds’ eye view
PDF
SpringOne Platform recap 정윤진
Kotlin: Why Do You Care?
The things we don't see – stories of Software, Scala and Akka
Building Mobile Apps with Android
Anko & Karamba in Kotlin by Bapusaheb Patil
Why scala is not my ideal language and what I can do with this
ScalaDays 2013 Keynote Speech by Martin Odersky
Power Up Your Build - Omer van Kloeten @ Wix 2018-04
Polyglot
Intro to OOP
3 little clojure functions
Coscup
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Introduction to meta-programming in scala
Sync considered unethical
Introduction to Qt
From Android NDK To AOSP
Kotlin for Android Developers - 1
Koin Quickstart
Monix : A Birds’ eye view
SpringOne Platform recap 정윤진
Ad

Recently uploaded (20)

PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Transform Your Business with a Software ERP System
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Essential Infomation Tech presentation.pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
medical staffing services at VALiNTRY
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
L1 - Introduction to python Backend.pptx
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Reimagine Home Health with the Power of Agentic AI​
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Transform Your Business with a Software ERP System
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Odoo POS Development Services by CandidRoot Solutions
Upgrade and Innovation Strategies for SAP ERP Customers
2025 Textile ERP Trends: SAP, Odoo & Oracle
Essential Infomation Tech presentation.pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Odoo Companies in India – Driving Business Transformation.pdf
Understanding Forklifts - TECH EHS Solution
CHAPTER 2 - PM Management and IT Context
medical staffing services at VALiNTRY
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
How to Migrate SBCGlobal Email to Yahoo Easily
L1 - Introduction to python Backend.pptx
Design an Analysis of Algorithms I-SECS-1021-03
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PTS Company Brochure 2025 (1).pdf.......
How to Choose the Right IT Partner for Your Business in Malaysia
Reimagine Home Health with the Power of Agentic AI​

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/

Editor's Notes

  • #2: Hi, My name is Alexey Soshin, I’m a Solutions Architect at Depop, And today we are gonna talk about mixing Scala and Kotlin
  • #3: 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?
  • #4: 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.
  • #5: Every time I even mention this talk, people ask me: but why would you even do that?! Well, there are a few reasons.
  • #6: 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.
  • #7: 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.
  • #8: 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
  • #9: 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
  • #10: 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
  • #11: So, let’s start with something that seems relatively simple. Compatibility between data structures
  • #12: 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.
  • #13: 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.
  • #14: 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!
  • #15: Those two have similar meanings, both indicate possible absence of value. But how can we integrate between them?
  • #16: 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.
  • #17: Kotlin extension methods to the rescue.
  • #18: I guess everybody here like functional programming. Functions are great. Let’s dive into that.
  • #19: 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?
  • #20: 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
  • #21: 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
  • #22: 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?
  • #23: 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.
  • #24: I guess everybody here like functional programming. Functions are great. Let’s dive into that.
  • #25: 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
  • #26: 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.
  • #27: 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.
  • #28: 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
  • #29: 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.