Balaji Krishnamoorthy
Balaji Krishnamoorthy

Reputation: 11

Scala .init method example

Can you please explain what init method performs with respect to below list i can see the result of new list says that last sequence is being omitted from the existing list.

val numbers = List(1, 2, 3, 4, 5)

val result = numbers.init
println(result)

Upvotes: 0

Views: 521

Answers (3)

Amit Prasad
Amit Prasad

Reputation: 725

def init: List[A] which selects all elements except the last.

l: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)

scala> l.last
res58: Int = 8

scala> l.init
res59: List[Int] = List(1, 2, 3, 4, 5, 6, 7)

Upvotes: 1

Kullayappa  M
Kullayappa M

Reputation: 174

scala> val testList = List(1,2,3,4,5)
 testList: List[Int] = List(1, 2, 3, 4, 5)

scala> testList.init
res0: List[Int] = List(1, 2, 3, 4)

scala> testList.last
res1: Int = 5

scala> testList.head
res2: Int = 1

scala> testList.tail
res3: List[Int] = List(2, 3, 4, 5)

Upvotes: 0

jwvh
jwvh

Reputation: 51271

.init and .last are the compliments to the .head and .tail methods.

val nums = List(1,2,3,4)

nums.head  //res0: Int = 1
nums.tail  //res1: List[Int] = List(2, 3, 4)

nums.init  //res2: List[Int] = List(1, 2, 3)
nums.last  //res3: Int = 4

Upvotes: 2

Related Questions