scala objects as fields

scala

Solution

Using an `object` may be preferable if you need to add behavior to the field. For example:

class Foo {
   object startDate extends java.util.Date {
      def isBusinessDay: Boolean = // ...
   }
}

class Bar {
   lazy val startDate = new java.util.Date {
      def isBusinessDay: Boolean = // ...
   }
}

The type of `foo.startDate` is `foo.startDate.type`, and a call to the `foo.startDate.isBusinessDay` method will be resolved statically.

The type of `bar.startDate`, on the other hand, is the structural type `java.util.Date{ def isBusinessDay: Boolean }`. A call to `bar.startDate.isBusinessDay` will therefore use reflection and incur unnecessary runtime overhead.

Problem

Possible Duplicate: val and object inside a scala class? Is there a substantive difference between: ``` class Foo { object timestamp extends java.util.Date } ``` and ``` class Foo { val timestamp = new java.util.Date {} } ``` What does it really mean to have a class with an object field? What are they used for? Are there situations where you must use an object? Thanks...

Original source

Related problems