Scala List apply() 方法与示例
apply()方法用于通过索引选择列表中的元素。
Method Definition: def apply(n: Int): A
Return Type: It returns an element from the given list by its index which is present in the apply method as argument.
示例 #1:
// Scala program of apply()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a list
val m1 = List(1, 3, 5, 2)
// Applying apply method
val res = m1.apply(3)
// Displays output
println(res)
}
}
输出:
2
示例 #2:
// Scala program of apply()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a list
val m1 = List(1, 3, 5, 2)
// Applying apply method
val res = m1.apply(0)
// Displays output
println(res)
}
}
输出:
1