What are views for collections and when would you want to use them?

前端 未结 4 1670
死守一世寂寞
死守一世寂寞 2020-12-07 22:09

In Scala, for many (all?) types of collections you can create views.

What exactly is a view and for which purposes are views useful?

4条回答
  •  旧时难觅i
    2020-12-07 23:02

    One use case is when you need to collect first result of elements transformation:

        case class Transform(n: Int) { println("Transform "+n)}
        val list = List(1,2,3,4,5)
        list.view.map(v => Transform(v)).collectFirst{case Transform(3) => println("found")}
    

    Prints:

    Transform 1
    Transform 2
    Transform 3
    found
    

    While:

        list.map(v => Transform(v)).collectFirst{case Transform(3) => println("found")}
    

    Prints:

    Transform 1
    Transform 2
    Transform 3
    Transform 4
    Transform 5
    found
    

提交回复
热议问题