samol samol - 27 days ago 8
Scala Question

How to make this method generic in Scala

This is a simple function which given an index, look up the item in an array from last

e.g. given

val arr = Array(1,2,3)
and
val i = 0
; it will return
3


def findIndexFromLast(arr: Array[Relationship], i: Int): Relationship = {
val cur = i
val size = arr.length

arr(size - i - 1)
}


I want to make it generic and be able to accept Array of any type

Answer

If you make the 1st argument a Seq(), it will take many different types of collections as input.

def fromEnd[T](coll: Seq[T], index: Int):T = coll.reverse(index)

fromEnd(Array(1,3,5,7,9), 0)                 // res0: Int = 9
fromEnd(List('x','y','q','b'), 3)            // res1: Char = x
fromEnd(Vector(2.2, 5.4, 7.7), 2)            // res2: Double = 2.2
fromEnd(Stream(true, true, false, true), 1)  // res3: Boolean = false