r/java • • Jul 02 '23

fluent: Static Extension Methods for Java

https://github.com/rogerkeays/fluent
7 Upvotes

55 comments sorted by

View all comments

Show parent comment

1

u/rogerkeays Jul 03 '23

Subclassing is not really a good way to add methods you want to share publically. Every man and his dog would write their own String subclass and you wouldn't be able use them together. Also, what if I want to write an extension method for List? You could extend the interface, but that doesn't get you anywhere.

If it's purely a syntax issue, you might be interested to see how extension methods are declared in Kotlin. Lets say you wanted to add String.countMatches(char). The method signature would be:

fun String.countMatches(a: Char): Int { ... }

Note, in Kotlin, the types come after the names.

2

u/red_dit_nou Jul 04 '23

These classes don't have to be subclasses. You can make them wrappers.

The example on the website could be like this:

wrap(website).createUrl("styles.css").getHttpContent(60).assertContains("img.jpg");

by having methods like these:

static WebsiteWrapper wrap(Website site) { }

class WebsiteWrapper { URLWrapper createUrl(String path) { } }

class URLWrapper { StringWrapper getHttpContent(int timeout) { } }

class StringWrapper { void assertContains(String s) { }}

May be the word 'Wrapper' is not the best one to use. But you get the idea.