- Use syntactic sugar and built-in functions to save bytes.
syntactic sugar, e.g. use /: operator (fold left)
val sum = numbers.foldLeft(0) { (accumulator, element) => accumulator + element }
val sum = (0 /: numbers) { (accumulator, element) => accumulator + element }
Type conversion.
231+.0
instead of231.toDouble
.231+""
instead of231.toString
Use
Seq
instead ofArray
orList
Rewrite type name and method name.
Rewrite the type name if the type appears very many times.
Use generic parameter instead of external type definition to save more bytes.
/*42 bytes*/
def f(a:String,b:String,c:String,d:String)
/*36 bytes*/
type S=String
def f(a:S,b:S,c:S,d:S)
/*33 bytes*/
def f[S<:String](a:S,b:S,c:S,d:S)
If the method appears very many times, please rewrite the method name.
implicit class V[A](val x:A)extends AnyVal{def Q=x.toSet}
Avoid
def
return type if possible. Usedef
instead of lambda functionval f=
. e.g.use
def f(a:Int)=a+1
instead ofval f:(Int=>Int)={a:Int=>a+1}
to save bytes.Avoid unnecessary braces
{} ()
Simultaneously initialize multiple variables
val r,c=new StringBuilder;
use
0to0 to x-1
instead of0 until x