get()方法用於提供與Map的鍵關聯的值。這些值在此處作為選項返回,即以“一些”或“無”的形式返回。
函數定義:def get(key: A): Option[B]
返回類型: It returns the keys corresponding to the values given in the method as argument.
範例1:
// Scala program of get()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a map
val m1 = Map("geeks" -> 5, "for" -> 3, "cs" -> 2)
// Applying get method
val result = m1.get("for")
// Displays output
println(result)
}
}
輸出:
Some(3)
在這裏,參數(即for)中的鍵存在於上述映射中,因此,鍵的值以Some格式返回。範例2:
// Scala program of get()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a map
val m1 = Map("geeks" -> 5, "for" -> 3, "cs" -> 2)
// Applying get method
val result = m1.get("portal")
// Displays output
println(result)
}
}
輸出:
None
此處,參數中的鍵不存在於映射中,因此,將返回None。
相關用法
- Scala Set contains()用法及代碼示例
- Scala Set -()用法及代碼示例
- Scala Set ++()用法及代碼示例
- Scala Set +()用法及代碼示例
- Scala Int to(end: Int)用法及代碼示例
- Scala Set &~()用法及代碼示例
- Scala Int self()用法及代碼示例
- Scala map()用法及代碼示例
- Scala Set last()用法及代碼示例
- Scala Set sum()用法及代碼示例
- Scala Set min()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Scala Map get() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。