To add an extension method to a singleton object in Scala 2, follow these steps:
object
keyword, and give it a name. For example:object MySingletonObject {
// define methods or properties here
}
def myExtensionMethod(singletonObj: MySingletonObject.type): String = {
"Hello, world!"
}
implicit
keyword before the method definition. For example:implicit def myExtensionMethod(singletonObj: MySingletonObject.type): String = {
"Hello, world!"
}
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.
Asked: 2023-01-31 11:00:00 +0000
Seen: 20 times
Last updated: May 16 '22