[英]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.我正在尝试动态生成一系列案例 class 但我一度被阻止。 I want to use variables in this function.
我想在这个 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:我现在要做的是在生成过程中将 first_name 和 last_name 作为变量,如下所示:
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.请注意,
Seq
是一个通用接口,因此您可能应该使用显式类型(例如List
或Vector
)来确保获得所需的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.