Pacific-Design.com

    
Home Index

1. Scala

2. Companion Objects

Scala / Companion Objects /

Creating Static Members with Companion Objects

// Pizza class    
class Pizza (var crustType: String) {

  override def toString = "Crust type is " + crustType

}

// Companion Pizza object
object Pizza {

  val CRUST_TYPE_THIN = "Thin"
  val CRUST_TYPE_THICK = "Thick"
  def getFoo = "Foo"

}

object Main extends App {

  println("------ Static -------"); 
  println(Pizza.CRUST_TYPE_THIN)
  println(Pizza.getFoo)

  println("------ Dynamic -------");                                                                                
  var p = new Pizza(Pizza.CRUST_TYPE_THICK)
  println(p)

}
/*
------ Static -------
Thin
Foo
------ Dynamic -------
Crust type is Thick
*/


Instance Object accessing private member of Static Object

class Foo {
  // access the private object field 'obj'
  def printObj { println(s"I can see ${Foo.obj}") }
}

object Foo {
  private val obj = "Foo's object"
}

object Driver extends App {
  val f = new Foo
  f.printObj
}
/*
I can see Foo's object
*/