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

Tips for golfing in Scala

+1
−0

What general tips do you have for golfing in Scala? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Scala (e.g. "remove comments" is not an answer).

This has been copied from a tips question on Code Golf SE.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

1 answer

+1
−0

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:

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:

//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
History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »