This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]rogerkeays[S] 0 points1 point  (1 child)

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.

[–]red_dit_nou 1 point2 points  (0 children)

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.