scala Range for Long

后端 未结 3 1018
长情又很酷
长情又很酷 2021-01-12 18:21

I\'m new to the Scala language.

I need Range for Long type.

I need a List of [1, 2, 3 ... 10000000] with step 1. If I use until/to I get an error because of

3条回答
  •  天涯浪人
    2021-01-12 19:17

    You probably do not need a range. I would take a Stream and iterate over it.

    def stream(i: Long = 1): Stream[Long] = i #:: stream(i + 1)
    

    produces an infinit Stream where the difference between the elements is 1. Because Stream is a lazy collection you will not gett any Errors. To iterate over 10000000 elements you simply use the following:

    val range = stream take 10000000
    for (i <- range) {
      ...
    }
    

    take 10000000 will return a Stream with size 10000000. Because Stream is an Iterable you can pass it to a for comprehansion.

提交回复
热议问题