Lazily evaluated indexed sequence type

前端 未结 3 1297
孤独总比滥情好
孤独总比滥情好 2021-01-04 20:42

I need to build a sequence of objects that are loaded from an external resource. This loading being an expensive operation needs to be delayed until the time the objects are

3条回答
  •  花落未央
    2021-01-04 21:23

    Strange, Miles recently tweeted about this. A reply then points out to Need at the end of Name.scala in scalaz and another one points to specs' LazyParameter.

    Little testing with Need:

    import scalaz._
    import Scalaz._
    val longOp = { var x = 0; () => {println("longOp"); x += 1; x }}
    val seq = Seq(Need(longOp()), Need(longOp()))
    val sum = seq.map(_.value).sum
    val sum = seq.map(_.value).sum
    
    val v = Need(longOp())
    val s = v.map("got " + _)
    println(s.value)
    println(s.value)
    

    prints:

    longOp: () => Int = 
    seq: Seq[scalaz.Name[Int]] = List(
      scalaz.Name$$anon$2@1066d88, scalaz.Name$$anon$2@1011f1f)
    longOp
    longOp
    sum: Int = 3
    sum: Int = 3
    v: scalaz.Name[Int] = scalaz.Name$$anon$2@133ef6a
    s: scalaz.Name[java.lang.String] = scalaz.Name$$anon$2@11696ec
    longOp
    got 3
    got 3
    

    So longOp is only called once on first access of value.

提交回复
热议问题