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

66%
+2 −0
Q&A Tips for golfing in Java

Abuse anonymous classes Warning: This only works in very specific circumstances, and I've never actually needed it. Instead of defining a method outside of your method, you can make an instance o...

posted 3y ago by user‭

Answer
#1: Initial revision by user avatar user‭ · 2021-10-13T14:45:04Z (about 3 years ago)
# Abuse anonymous classes

Warning: This only works in very specific circumstances, and I've never actually needed it.

Instead of defining a method outside of your method, you can make an instance of an anonymous class to act as a closure. This'll only really help if what the method is closing over has a very long type or name. Here's an extremely contrived example where an extra method is defined because recursion is needed.

```java
int g(List<Integer>b){return new Object(){int f(int x){return x>b.get(0)?f(x-1)*2:1;}}.f(3);}
```
The one above is 93 bytes, the one below is 97.
```
int g(List<Integer>b){return f(b,3);}int f(List<Integer>b,int x){return x>b.get(0)?f(b,x-1)*2:1;}
```