Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice notation in Scala?

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.

like image 448
Emil Avatar asked Oct 14 '10 11:10

Emil


People also ask

What is Scala slice?

The slice function is applicable to both Scala's Mutable and Immutable collection data structures. The slice method takes a start and end index and will use them to return a new collection with elements that are within the start and end index range.

How to slice Array in Scala?

In Scala API, 'slice' function is used to select an interval of elements. It takes two parameters of “Int” type and returns subset or whole or none element(s) of original Collection (or String or Array). Real-world slice scenario:- We can use this slice function in our regular real-world life too as shown below.

What is a slice notation?

Slice notation allows you to skip any element of the full syntax. If we skip the start number then it starts from 0 index: >>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]

How do I append to a list in Scala?

This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.


1 Answers

Equivalent method in Scala (with a slightly different syntax) exists for all kinds of sequences:

scala> "Hello world" slice(0,4) res0: String = Hell  scala> (1 to 10) slice(3,5) res1: scala.collection.immutable.Range = Range(4, 5) 

The biggest difference compared to slicing in Python is that start and end indices are mandatory in Scala.

like image 145
Vasil Remeniuk Avatar answered Sep 19 '22 15:09

Vasil Remeniuk