search term:

Scala, Python quick reference

syntax Scala Python
immutable variable val x = 1 Starlark:
REV = "1.1.0"
lazy variable lazy val x = 1 n/a
mutable variable var x = 1 in function:
x = 1
if expression if (x > 1) "a" else "b" "a" if x > 1 else "b"
———————- —————————- —————————-
function def add3(x: Int): Int =
x + 3
def add3(x):
return x + 3
anonymous function _ * 2 not in Starlark:
lambda x: x * 2
———————- —————————- —————————-
List val xs = List(1, 2, 3, 4) xs = [1, 2, 3, 4]
size xs.size len(xs)
empty test xs.isEmpty not xs
head xs.head xs[0]
tail // List(2, 3, 4)
xs.tail
# [2, 3, 4]
xs[1:]
take // List(1, 2)
xs.take(2)
# [1, 2]
xs[:2]
drop // List(3, 4)
xs.drop(2)
# [3, 4]
xs[2:]
drop right // List(1, 2, 3)
xs.dropRight(1)
# [1, 2, 3]
xs[:-1]
nth element xs(2) xs[2]
map xs.map(_ * 2)

for {
x <- xs
} yield x * 2
map(lambda x: x * 2, xs)

[x * 2 for x in xs]
filter xs.filter(_ % 2 == 0)

for {
x <- xs if x % 2 == 0
} yield x
filter(lambda x: not x % 2, xs)

[x for x in xs if not x % 2 ]
fold from left // "a1234"
xs.foldLeft("a") { _ + _ }
from functools import reduce
# "a1234"
reduce(lambda a,x: a + str(x), xs, "a")
membership xs.contains(3) 3 in xs
———————- —————————- —————————-
String val s = "hello" s = "hello"
variable interpolation val count = 3
s"$count items"
not in Starlark:
count = 3
f"{count} items"
split // Array(1.2.3, M1)
"1.2.3-M1".split("-")
# ['1.2.3', 'M1']
"1.2.3-M1".split("-")
substring test s.contains("el") "el" in s
———————- —————————- —————————-
Map val d = Map("a" -> 1,
“b” -> 2)
d = { "a": 1, "b": 2 }

notes

I’m picking up Python and its Bazel dialect Skylark lately. On the other hand, I’m familiar with Scala and its sbt dialect. Often I know exactly what I want to express, and I am fairly certain Python has the equivalent concept as Scala, but just don’t remember the exact incantation. For people starting Scala, maybe they could use this table in reverse.