Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Post History

60%
+1 −0
Q&A Tips for golfing in Scala

Making a function with val can be shorter than with a def If you're pattern matching, you can use Scala's special syntax and omit match when assigning an anonymous function to a val. As you can se...

posted 3y ago by user‭

Answer
#1: Initial revision by user avatar user‭ · 2021-04-02T20:16:38Z (about 3 years ago)
# Making a function with `val` can be shorter than with a `def`

If you're pattern matching, you can use Scala's special syntax and omit `match` when assigning an anonymous function to a `val`. As you can see, it's a lot shorter:
```scala
val g:List[Int]=>Int={case h::t=>h+g(t)case _=>0}
def f(l:List[Int]):Int=l match{case h::t=>h+f(t)case _=>0}
```

You can also use underscore syntax. For certain functions, this is always profitable. For others, like the example below, where the type of the parameter cannot be inferred, it is only profitable when you have only one parameter with a type ascription.
```
val g=(_:Int)+1
def f(i:Int)=i+1
```

However, if you need to reuse a function, make a `def` instead of a `val`. Consider these two pairs of functions:
```scala
//Recursive
def f(i:Int):Int=if(i>0)i*f(i-1)else 1
val f:Int=>Int=i=>if(i>0)i*f(i-1)else 1

//Non-recursive functions are also shorter with def
def f(i:Int)=i+1
val g=(i:Int)=>i+1
```