← home

Objects in Scala

Object example in Scala:

(creating unique account nums starting from 2100000 at various places in the relative app)

object Acconuts:
    private var accountNumber = 2100000
    def newUniqueAccNumber()=
    accountNumber += 1 
    accountNumber

Using objects in Scala:

Accounts.newUniqueAccNumber() // 2100001
Accounts.newUniqueAccNumber() // 2100002
Accounts.newUniqueAccNumber() // 2100003

Static Fields and Methods

Static example in java:

public class Person{
    public static int numberOfPeople;
    
    public static int getNumOfPeople(){
        return Person.numberOfPeople;
    }
    
    public person(){
        numberOfPeople++;
    }
}

You see, this is pretty shit. Scala does this more elegantly

Static example in Scala using "companion objects"

Companion object example:

Person class:

class person(val name: String):
    person.incrementNumPeople // constructor just calls incrememnt method on companion object

companion object for person class (is a replacement for static in java)

object Person:
    var numofPeople = 0
    private def incrmementNumPeople = numOfPeople =+ 1
    def conut = numOfPeople

usage:

var p1 = Person("Jake")
var p2 = Person("Yosra")
println(s"count: #{Person.count}") //outputs 2

Apply Method in Scala

Basic Example:

We can create objects like this:

val foo = new Foo

Treating foo like a function...

foo()

foo obj:

def foo:
    def apply() println(s"foo being foo")

Another example:

object Greet:
    def apply(val name: String) = 
        println(s"gm {name}") 

proxying the companion object

class City(val name: String) //class

object City:                 //companion object
   def apply(name: String)
        new City(name)

New "city" object will appear if you change the following:

    City("dublin")
← home