很好地创建一个对象列表

rle*_*ndi 0 scala scala-collections

我想知道创建一个List对象最好的方法是什么.

我能想到的是将用于转换RangeList:

val objs: List[String] =
  for (i <- 1.to(100).toList)
    yield new String("" + i)
Run Code Online (Sandbox Code Playgroud)

或转换整个结果toList:

val objs: List[String] =
  (for (i <- 1 to 100 )
    yield new String("" + i)).toList
Run Code Online (Sandbox Code Playgroud)

但它们对我来说都不够光滑.有没有更简单的方法来做到这一点?变量必须是类型的,List因为它在我正在使用的代码中的其他地方使用.提前致谢!

dhg*_*dhg 6

您可以toList直接在Range上使用.

(1 to 100).toList
Run Code Online (Sandbox Code Playgroud)

要将Int转换为字符串,只需使用toString并将其映射到范围:

(1 to 100).map(_.toString).toList
Run Code Online (Sandbox Code Playgroud)

此外,您的使用new String("" + i)实际上是多余的.表达式"" + i 已经是String,因此您实际上是从现有String中创建一个新String.所以你应该只使用现有的String!

如果你真的更喜欢"" + i语法toString,你应该至少这样做:

(1 to 100).map("" + _).toList
Run Code Online (Sandbox Code Playgroud)

编辑:基于你关于真正想要摆脱toList电话的评论,你可以使用breakOut.这通过查看期望的类型(在此处等号的左侧指定)并直接创建该类集合来工作.好处是它避免了在创建map之前创建一个中间集合(from )List,但它更加丑陋.

val xs: List[String] = (1 to 100).map(_.toString)(breakOut)
Run Code Online (Sandbox Code Playgroud)

或者,如果你想要"" + _语法

val xs: List[String] = (1 to 100).map("" + _)(breakOut)
Run Code Online (Sandbox Code Playgroud)

或者,与你原先想要的for/yield一样:

val xs: List[String] = (for(i <- 1 to 100) yield "" + i)(breakOut)
Run Code Online (Sandbox Code Playgroud)