Pratik Khadloya
Pratik Khadloya

Reputation: 12869

Scala val and type at the same time

While reading Scala source code i came across the following in scala/package.scala I don't quite get why we need trait and val at the same time. The trait keyword will alias the class, then why do we need the val ?

  type StringBuilder = scala.collection.mutable.StringBuilder
  val StringBuilder = scala.collection.mutable.StringBuilder

  // Numeric types which were moved into scala.math.*

  type BigDecimal = scala.math.BigDecimal
  val BigDecimal = scala.math.BigDecimal

  type BigInt = scala.math.BigInt
  val BigInt = scala.math.BigInt

  type Equiv[T] = scala.math.Equiv[T]
  val Equiv = scala.math.Equiv

Am including a Generic Type example as well to get more understanding about the multiple declarations there was well.

Upvotes: 3

Views: 58

Answers (1)

Ben Kovitz
Ben Kovitz

Reputation: 5020

It's because type only defines a type alias; it doesn't alias the type's companion object.

The companion object usually contains handy methods, especially an apply method for creating objects of the type. If you don't do the val, you won't have access to those methods, at least not under the name of the alias.

Upvotes: 7

Related Questions