DEV Community

langyizhao
langyizhao

Posted on • Updated on

Kotlin Scala Differences Cheat Sheet

Feature Kotlin Scala
Function Keyword fun def
Nullability Default not nullable except by adding ? at the end of variable type Null is discouraged, but no hard check
Null Check Use ?. and/or ?: Use Option
Lambda/Anonymous Functions Need to be surrounded with {} Can be used anywhere
Covariant [out T] [+T]
Contravariant [in T] [-T]
Pattern Matching (partial) when statement (full) match/case
Default Case else -> case _ =>
Loop a Range i in 1..10 step 2 (closed) i in 1 until 10 step 2 (half-closed) i <- 1 to 10 by 2 (closed) i in 1 until 10 by 2 (half-closed)
Read File into Strings File(fileName).useLines { it.toList() } scala.io.Source.fromFile("file.txt").mkString
For Comprehension (for/yield) No Equivalent Supported
Companion Object companion object keyword inside class object keyword besides class
New Immutable Sequence listOf("one", "two", "one") Seq("one", "two", "one")
New Immutable Set setOf("one", "two", "three") Set("one", "two", "one")
New Immutable Map mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1) Map("key1" -> 1, "key2" -> 2, "key3" -> 3, "key4" to 1)
Top Level Functions (Package Level) Supported Will be supported in Scala 3
Extension Functions fun Any?.toString(): String { if (this == null) {return "null"} return toString()} extension (c: Circle) def circumference: Double = c.radius * math.Pi * 2
Operator Overloading with operator infix keyword operators are just normal functions
Regex String "[0-9]".toRegex() "[0-9]".r
Tuple 2 Pair(a, b) (a, b)
Tuple 3 Triple(a, b, c) (a, b, c)
Destructuring Assignment Objects with componentN() (data classes and collections) Objects with unapply() (extractors like case classes)
Tail Recursive Function tailrec keyword @tailrec annotation
Multiple Inheritance Resolution Must override function in question manually Later trait wins
Class Inheritance only with open or abstract keyword allowed
The sealed keyword sealed class is something like enum sealed types are confined in its source file
Secondary/Auxiliary Constructors constructor keyword this() functions
Reference Equality (the Java ==) === eq
Map Entry Literal k to v k -> v

Top comments (0)