by aliakhtar · 6y ago · 0 comments
1) Main
def main() = println("Hello")
2) Variables:
val y = 1
3) Options (nulls are discouraged):
val name: Option[String] = None
4) Null 2:
//If bob is not null, get his age, or get a default age
val age = bob.map(_.age).getOrElse(0)
5) Elvis operator
Kotlin:
val result = nullableVariable?.someMethodCall() ?: fallbackIfNullMethodCall()
Scala:
val result = option.map(_.someCall()).getOrElse(defaultValue)
6) String interpolation in scala seems to be exactly the same as kotlin:
val name = "John"
val lastName = "Smith"
val text = "My name is: $name $lastName"
val otherText = "My name is: ${name.substring(2)}"
In addition, you can also have:
val longString = s"""
|This is line 1
|This is line 2, my name is $name
""".stripMargin
7) This shows the same multi-line strings as above, but its unclear if you can have variables in multi-line strings like I showed above in Scala
8) Ternary operator:
val text = if (x > 5) "x > 5" else "x <= 5"
Some bonus stuff which scala has:
9) Case classes:
case class Person(name: String, age: Int)
10) Pattern matching
person match {
case Person("bob", 13) =>
println("Matched bob with age 13")
case Person("sally", _) =>
println("Matched sally, age unknown")
case Person(name,age) =>
println(s"Matched unknown person with name $name and age $age")
case x:_>
println(s"Matched unknown item: $x")
}10) Equality which actually makes sense, i.e
val foo = "foo"
val bar = "foo"
foo == bar //true in scala, no need to foo.equals(bar)
val bob = Person("bob", 13)
val other = Person("bob", 13)
bob == other //true, based on values
val list = Seq(bob)
list.contains(other) //true, based on values
11) .par collections / way better higher order functions
val list = Seq(string1, string2,...)
//Do a parallelized search on list to find all strings <= 3 chars in length:
val shortStrings = list.par.filter(_.length <= 3).seq
12) Try:
val riskyOp = Try( doSomethingRisky() )
riskyOp match {
case Success(result) =>
println(s"Op succeeded with result $result")
case Failure(e) =>
e.printStackTrace
}Disclaimer: I wrote all these in the HN textbox, please excuse any typos
I'm genuinely interested, having spent the last few years with Haskell and having recently rediscovered and being incredibly awed by the JVM and its ecosystem, and pondering on whether I should refresh what I'd known of Java or just outright embrace Scala.
I don't have the time to convert their whole site right now, sorry, but you'll find the same pattern holds - Scala does everything more elegantly and concisely. Feel free to look up a Scala tutorial.