简体   繁体   中英

Scala : Create multiple sequence of case class with variables in it

I'm trying to generate dynamically a sequence of case class but I'm blocked at one point. I want to use variables in this function.

Here's an example of what I did (which is working as expected):

case class Example(first_name: String, last_name: String)

Object Example{
 def createRecords(number: Int) : Seq[Example]{
     Seq.fill(number)(Example("Bob", "Marley"))
}}

The thing I want to do now is to have the first_name and the last_name as variables in the generating process that would look like something like this:

Object Example{
 def createRecords(number: Int) : Seq[Example]{
     Seq.fill(number)(
        val first_name = generateRandomFirstName()
        val last_name = generateRandomLastName() 
        Example(first_name, last_name))
}}

Is there an easy way to be able to do that or I need to simply refactor my code and generate what I need with a standard loop?

Thanks in advance

Your code is actually very close, you just need to replace () with {} to turn the argument into an expression:

Seq.fill(number){
  val first_name = generateRandomFirstName()
  val last_name = generateRandomLastName()

  Example(first_name, last_name)
}

You can also just call the functions in the constructor:

Seq.fill(number)(
  Example(generateRandomFirstName(), generateRandomLastName())
)

Note that Seq is a generic interface so you should probably use an explicit type such as List or Vector to make sure you are getting the type you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM