Felix Mulder
“Scala is a better Java, type inference!”
“Liek OMG, a monad’s just a monoid in the category of endofunctors”
“There is not agreement on what is ”best“, so all we can really do is try to find a local optimum. But finding that optimum is what drives me”
def foo {}
// error!
def foo = {}
// res: Unit
But there’s a flag for that: -language:Scala2
A & B
is the greatest lower bound: a supertype of all subtypes of both A and BA | B
is the least upper bound: a subtype of all supertypes of both A and Bcase object Monday
case object Tuesday
case object Wednesday
case object Thursday
case object Friday
case object Saturday
case object Sunday
type Weekend = Saturday.type | Sunday.type
type Weekday = Monday.type | Tuesday.type...
type AnyDay = Weekday | Weekend
(Saturday: Weekend) match {
case Sunday => // incomplete!
}
trait A {
def foo: Int
}
trait B {
def bar: Int
}
def baz(ab: A & B) = ab.foo + ab.bar
trait Super {
def x: String
println(x)
}
class Foo extends Super {
val x = "hello"
}
new Foo
// prints: null
trait Super(x: String) {
println(x)
}
class Foo extends Super("hello")
new Foo
// prints: "hello"
@rewrites object rules {
def customFancyWarning(x: Int | Double | ... | Numeric[_]) =
Warn(pattern = x / 0,
msg = "division by zero, you fool!")
}
public double average(int[] data) {
int sum = 0;
for(int i = 0; i < data.length; i++) {
sum += data[i];
}
return sum * 1.0d / data.length;
}
def average(xs: Array[Int]) =
xs.reduce(_ + _) * 1.0 / xs.size
Java | Scala |
45 msec | 872 msec |
public double average(int[] data) {
int sum = 0;
for(int i = 0; i < data.length; i++) {
sum += data[i];
}
return sum * 1.0d / data.length;
}
def average(xs: Array[Int]) =
xs.reduce(_ + _) * 1.0 / x.size
def reduce(op: Function2[Obj, Obj, Obj]): Obj = {
var first = true
var acc: Obj = null
this.foreach { e =>
if (first) {
acc = e
first = false
} else acc = op.apply(acc, e)
}
acc
}
def foreach(f: Funtion1[Obj, Obj]) {
var i = 0
val len = length
while (i < len) {
f.apply(this(i))
i += 1
}
}
def plus[T](a: T, b: T)(implicit num: Numeric[T]): T =
num.plus(a, b)
def plus(a: Object, b: Object, num: Numeric): Object =
num.plus(a, b)
plus(1, 1)
unbox(plus(box(1), box(1), intNum))
trait T[A1, A2, ..., An]
how many combinations?
trait T[A1, A2, ..., An] {
def foo[B1, B2, ..., Bm] = ???
}
and now?
@specialized
def foo[@specialized A](a: A) = ???
Creates one version for each of Scala’s 9 primitives:int
, long
, short
, byte
, char
, float
, double
, boolean
, "void"
@specialized
@specialized(Int)
trait Function3[-T1, -T2, -T3, +R]
def foo[T](x: Seq[T], id: Int) = x(id)