scala - Choosing the last element of a list -
scala> last(list(1, 1, 2, 3, 5, 8)) res0: int = 8
for having result above, wrote code:
val yum = args(0).toint val thrill: def last(a: list[int]): list[int] = { println(last(list(args(0).toint).last) }
what problem code?
you can use last
, returns last element or throws nosuchelementexception
, if list empty.
scala> list(1, 2, 3).last res0: int = 3
if not know if list empty or not, may consider using lastoption
, returns option
.
scala> list().lastoption res1: option[nothing] = none scala> list(1, 2, 3).lastoption res2: option[int] = some(3)
your question list
, using last
on infinite collection (e.g. stream.from(0)
) can dangerous , may result in infinite loop.
Comments
Post a Comment