In ruby it's quite easy to implement a static method in its class.

 irb(main):001:0> class Array
irb(main):002:1> def self.mytest(li)
irb(main):003:2> li.reverse
irb(main):004:2> end
irb(main):005:1> end
=> :mytest

irb(main):006:0> li=[1,2,3,4]
=> [1, 2, 3, 4]

irb(main):007:0> Array.mytest(li)
=> [4, 3, 2, 1]

But in scala it has to declare a singleton to simulate static method in class, such as this one.

 scala> :paste
// Entering paste mode (ctrl-D to finish)

class Account {
val id = Account.newUniqueNumber()
private var balance = 0.0
def deposit(amount: Double) = { balance += amount }
object Account { // The companion object
private var lastNumber = 0
private def newUniqueNumber() = { lastNumber += 1; lastNumber }

// Exiting paste mode, now interpreting.

class Account
object Account

In the code above, there is no such static mehtod Account.newUniqueNumber for class Account.

But it declares an object (with the same name as class) within which the method newUniqueNumber is defined.

When calling Account.newUniqueNumber the method in singleton object is called actually.

Return to home | Generated on 10/12/22