Monkeying Around

Another approach that some languages have used is to allow developers to add functions to existing classes, including those that might be supplied as part of some standard library. That would allow you to, say, have an isValidEmail() function on String itself:

println("martians-so-do-not-exist@commonsware.com".isValidEmail())
println("this is not an email address".isValidEmail())

In the case of JavaScript, this is merely a matter of extending the prototype of the desired class:

String.prototype.isValidEmail = function() {
  // TODO implementation goes here
}

In Ruby, you can accomplish a similar thing, often referred to as “monkey-patching” a class:

class String
  def isValidEmail
    # TODO implementation goes here
  end
end

In both cases, isValidEmail() is added to that environment’s String type, so you can call isValidEmail() directly on a String object.

Kotlin supports this too, via what are known as extension functions. In fact, lots of stuff in Kotlin’s standard library is implemented via extension functions, instead of by implementing the functions directly on the affected types.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.