Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To add an extension method to a singleton object in Scala 2, follow these steps:

  1. Define the singleton object: Define your singleton object using the object keyword, and give it a name. For example:
object MySingletonObject {
  // define methods or properties here
}
  1. Define the extension method: Define the method you want to add as an extension method on the singleton object. This should be a method that takes the singleton object itself (as its first parameter) and returns some value. For example:
def myExtensionMethod(singletonObj: MySingletonObject.type): String = {
  "Hello, world!"
}
  1. Make the extension method implicit: To allow the extension method to be called on the singleton object, you need to make it an implicit method. Add the implicit keyword before the method definition. For example:
implicit def myExtensionMethod(singletonObj: MySingletonObject.type): String = {
  "Hello, world!"
}
  1. Use the extension method: You can now call the extension method on the singleton object just like any other method that is defined on the object. For example:
val myResult = MySingletonObject.myExtensionMethod
println(myResult)   // prints "Hello, world!"

Note that in Scala 2, extension methods are implemented using implicit conversions. When you make an extension method implicit, you are essentially adding a conversion from the object type to the return type of the method. The compiler will automatically call this conversion when you call the extension method on the object.