Scala objects like fields

Possible duplicate:
val and object inside scala class?

Is there a significant difference between:

class Foo {
  object timestamp extends java.util.Date
}

and

class Foo {
  val timestamp = new java.util.Date {}
}

What does it mean to have a class with an object field? What are they used for? Are there situations where you should use an object?

Thank...

+3
source share
3 answers

Use objectmay be preferred if you need to add behavior to the field. For instance:

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

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

Type foo.startDate- foo.startDate.type, and the method call foo.startDate.isBusinessDaywill be resolved statically.

A type bar.startDate, on the other hand, is a structural type java.util.Date{ def isBusinessDay: Boolean }. Thus, the call bar.startDate.isBusinessDaywill use reflection and carry unnecessary overhead.

+6

, , . -, . ,

class Foo {
  lazy val timestamp = new java.util.Date {}
}

. , . timestamp Foo.timestamp.type. , , .

+5

. , class X { object Y ... } X.Y. Y () , X, , X.Y. , X, , .

+2

Source: https://habr.com/ru/post/1779268/


All Articles