0

It's been a while since I've used constructors at all- so naturally when I have to use one in Scala I'm having trouble.

I want to do the following: When I create a new class without passing through anything- it creates an empty vector.

Otherwise if it passes through a vector- we use that vector and define it to be used with the class.

How do I do this? I previously had

Class example{ 

val a: Vector[int] = Vector();

Then I'm lost. I was thinking of doing something like

Class example{ 


val a: Vector[Int] = Vector() 


def this(vector: Vector[Int]){ 
  this{ 
   a = vector
  }
 }

But I'm getting tons of errors. Can anyone help? I'm trying to find my scala book but I can't find it- I know it had a good section on constructors.

chevybow
  • 6,960
  • 6
  • 23
  • 37

3 Answers3

6

Sounds like you want a constructor with a default argument:

class example(val a : Vector[Int] = Vector())
Thilo
  • 250,062
  • 96
  • 490
  • 643
6

If you really want to do this by constructor overloading, it looks like this:

class Example(val a: Vector[Int]) {    
  def this() = this(Vector())
}

Personal-opinion addendum: Overloading and default arguments are often good to avoid. I'd recommend just making a different function that calls the constructor:

class Example(val a: Vector[Int])

object Example {
  def empty = new Example(Vector())
}
Chris Martin
  • 29,484
  • 8
  • 71
  • 131
0
case class Example(a: Vector[Int] = Vector())

No need to put the val keyword.

Also, using the case keywork you get:

  • a compact initialisation syntax: Example(Vector(1,2)), instead of new Example(Vector(1,2))

  • pattern matching for you class

  • equality comparisons implicitly defined and pretty toString

Reference

Community
  • 1
  • 1
Onilton Maciel
  • 3,419
  • 1
  • 21
  • 28