Slice notation in Scala?

后端 未结 4 2078
轮回少年
轮回少年 2020-12-14 15:38

Is there something similar to the slice notation in Python in Scala?

I think this is really a useful operation that should be incorporated in all languages.

4条回答
  •  旧时难觅i
    2020-12-14 16:18

    Note that this does not quite work by using apply, but it generalizes to lists, strings, arrays, etc:

    implicit def it2sl[Repr <% scala.collection.IterableLike[_, Repr]](cc: Repr) = new {
      def ~>(i : Int, j : Int) : Repr = cc.slice(i,j)
    }
    

    The usage is:

    scala> "Hello World" ~> (3, 5)
    res1: java.lang.String = lo
    
    scala> List(1, 2, 3, 4) ~> (0, 2)
    res2: List[Int] = List(1, 2)
    
    scala> Array('a', 'b', 'c', 'd') ~> (1, 3)
    res3: Array[Char] = Array(b, c)
    

    You might want to rename the method to something else that takes your fancy. Except apply (because there is already a conversion from String to StringLike which decorates String with an apply method - similarly with ArrayOps - and there is already an apply method on other collection types such as List).

    Thanks for Daniel for the hint to use a view bound.

提交回复
热议问题