The static method in a class can be called without an instance but via the direct class name.

Here is the implementation in Scala:

 object Foo {
var int = 0
def increase = { int += 1; int }
}

println(Foo.increase)
println(Foo.increase)
println(Foo.increase)

The run results:

 $ scala t2.scala 
1
2
3

This is Ruby code for which I don't know if it's best written but it does work.

 class Foo
def self.count
@x ||= 0
@x += 1
@x
end
end

puts Foo.count
puts Foo.count
puts Foo.count

And the last is Perl code.

 use strict;
use warnings;

package A;

sub count {
our $int ||= 0;
$int ++;
return $int;
}

1;

package B;

print A->count,"\n";
print A->count,"\n";
print A->count,"\n";

For this implementation, perl and ruby are similar. They require to define a global variable for holding that increment value. Though both perl and ruby community don't suggest you to use a global variable.

IIRC perl calls this as a closure, while scala and ruby call it as singleton.

Return to home | Generated on 10/14/22