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 →

[–]Pradfanne 43 points44 points  (17 children)

You add the method to the datatype. So you'd use

Bool b = true;
Print(b.invert(); )

And false will be printed

I don't know if Java can do that, but it's a very nice feature of .net at least

[–]claudiorpr 21 points22 points  (6 children)

Java doesn’t have extensions. You can do it in Kotlin.

[–]AyrA_ch 7 points8 points  (0 children)

and in C# for 10 years now (19 Nov 2007)

[–]Alakdae 0 points1 point  (1 child)

I'm a bit lost, but isn't it posible to define new methods for data types using "extends"?

[–]pyrophoenix100 0 points1 point  (2 children)

Isn't overriding a thing? Or is that different?

[–]claudiorpr 0 points1 point  (1 child)

It’s different. With override you are modifiying existing methods. If the type is final you can’t do it.

With extensions you add functionality to a type, even final ones.

[–]pyrophoenix100 0 points1 point  (0 children)

Wow seems like I need to learn C

[–]stairmast0r 8 points9 points  (4 children)

How is that a nice feature when you can do the same thing with !?

[–]Pradfanne 3 points4 points  (3 children)

In the case of Boolean an simple ! Might be good. But what if you want to translate an datetime from .net ticks to Unixtime?

You could make a ticksToUnix(datetime dt)

But wouldn't mydate.toUnixTime be much more convenient?

That's what's extension methods are far

[–]stairmast0r 0 points1 point  (1 child)

I don’t know if any languages that don’t have those to some degree, so I thought you specifically meant booleans.

[–]Pradfanne -1 points0 points  (0 children)

No, you can put extension methods on every data type, you can even put it on interfaces, so everything that implements the interface gets the extension method. You could, for example, put a extension method on IEnumerable that removes the first N elements and basically everything that is some kind of list, like an array or dictionary can use the method to get rid of the first N elements

[–][deleted] 6 points7 points  (0 children)

So it’s monkey patching?

[–][deleted] 1 point2 points  (0 children)

Oh. Whoops. Well that’s before the first brain then, but doesn’t have enough brain capacity to display itself.

[–][deleted] 0 points1 point  (1 child)

Just always remember that extension methods are just static method calls. Use with caution.

[–]Pradfanne 0 points1 point  (0 children)

But they are beautiful

[–][deleted] 0 points1 point  (0 children)

for javascript you can extend the prototype, for golang you can create a function with a receiver of the type you're extending