Use match types for recursive functions that pattern match
Making a typealias with a match type is sometimes shorter than using a proper function. For example, take this implementation of the KI calculus (not an actual thing). The type doesn't need :Any
, so you save 7 bytes in all (type
is 1 byte more than def
).
//A normal function
def r(t:Any):Any=t match{case(('K',x),y)=>r(x)case('I',x)=>r(x)case t=>t}
//With match types
type R[T]=T match{case(('K',x),y)=>R[x]case('I',x)=>R[x]case _=>T}
Admittedly, in this particular example, you could use auto-tupling, ->
, pattern-matching function literals, etc. to make the def shorter, but this is just one case. When you're not dealing with tuples, or the return type is more complex than just Any
, or you have multiple parameters, this tip becomes more useful.
Use type constructors for two-argument functions
When you define a type with two type parameters, you can treat it like an infix operator. Not so for methods. Suppose you have the following two definitions
def>(a:Int,b:Int)=...
type +[A,B]=...
When you invoke >
, you can call it with >(a,b)
, whereas for +
, you can call it like A+B
. You can use any other operator you want if you want a specific precedence.