Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there other languages that have something like Swift's extensions?

In Swift, an extension is a way to define members for classes after the fact. Or, you could say, it is (coming from a total newb) fancy way of composing a function:

extension Double {
    var mm: Double { return self * 1_000.0 }
    func mm1() -> Double { return self * 1_000.0 }
}

func mm(a: Double) -> Double {
    return a * 1_000.0
}

print("One meter is \(1.mm) milimeters")
print("One meter is \(1.mm1()) milimeters")
print("One meter is \(mm(1)) milimeters")

I have never seen something like this. Is there anything like this in any other languages?

like image 386
hgiesel Avatar asked Oct 19 '22 10:10

hgiesel


1 Answers

Yes other languages have features like extensions. As @hnh points out C# has a very similar feature

It also makes it clear this feature is not "monkey patching"

Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type

To put it another way extensions are more like a syntactic sugar. Given the example in the question, Double, you could just make a function that takes a Double (as shown in the question)

func mm(a: Double) -> Double {
    return a * 1_000.0
}

And then you could call it directly

var foo = 12.34;
print("One meter is \(mm(foo)) millimeters")

What effectively happens with extensions in both C# and Swift is the extension tells the compiler to translate behind the scenes

someDouble.mm()

into

mm(someDouble)

or in our case more like

__extension_for_type_Double_mm(someDouble as self)

So, nothing is patched.

This also means you can have more than one mm extension from different modules and choose which one to use per file by only importing that module in that file where as some other file can import another module with another extension for the same type with the same name. This is not possible with monkey patching because the object or its class/prototype gets patched (something actually changes). Here, nothing changes, it's just syntactic sugar for calling a stand alone function.

This means features like monkey-patching in Ruby and JavaScript are not the same as extensions.

like image 65
gman Avatar answered Dec 11 '22 03:12

gman