david hol
david hol

Reputation: 1280

How to auto generate object when the class get no params

So i have simple class named Person, this class have several fields:

class person {

val name:String
val abe:Int

  def generateRandom(): Person {

     // Here i want to generate Person and return
  }
}

So as you can see i want my class will have the option to generate random Person but i don't want to pass any params to my class, i want it to be auto. So how can i create new Person object inside this generateRandom method and return it with both name and age fields ? Any suggestions how to implement it ?

Upvotes: 0

Views: 68

Answers (3)

Marek Adamek
Marek Adamek

Reputation: 520

You use val for name and age, so there's no other way - you have to set then in constructor. However you can make constructor private and move generator method to companion object (because it can access private constructor). The code would look like this:

class Person private (val name: String, val age: Int)

object Person {
  def generateRandom(): Person = {
    val randomName = ...
    val randomAge = ...
    new Person(randomName, randomAge)
  }
}

//new Person("asdas", 3) not possible

val person = Person.generateRandom()
println(person.name, person.age)

Upvotes: 1

Venu prasad H S
Venu prasad H S

Reputation: 241

It seems very simple.

Just return the new Person object from the method, adding some random value to Name and Age.

Upvotes: 0

kpie
kpie

Reputation: 11100

I think you need to have param: String = null in your parentheses. With the accompanied if(param == null)... Scala default parameters and null

Upvotes: 0

Related Questions