Mam*_*uka -1 dictionary types functional-programming scala
当我从类型的地图中获取元素时Map[Int,Int],我得到了Some(24),我不能使用+,-,*,/它的操作,因为它不是Int.你能告诉我如何Int从该地图中获取类型值而不是Some(24)?
那是因为Map.get( key )回归了Option.
您可以使用以下更安全的方法,
你可以使用模式匹配,
val yourIntOption: Option[ Int ] = yourMap.get( "someKey" )
// yourIntOption will be Some( i ) if key found or None if no such key.
yourIntOption match {
case Some( i ) => println( i + 1 )
case None => println( "None" )
}
Run Code Online (Sandbox Code Playgroud)
或者,你可以选择呆在里面Option monad,
val yourIntOption: Option[ Int ] = yourMap.get( "someKey" )
val intOptionAfterAdding: option[ Int ] = yourIntOption.map( i => i + 1)
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用以下不安全(可以抛出异常)方法
val yourInt = yourMap( "someKey" )
// will throw a NoSuchElementException if this key is not found.
Run Code Online (Sandbox Code Playgroud)
要么,
val yourIntOption: Option[ Int ] = yourMap.get( "someKey" )
val yourInt = yourIntOption.get
// will throw a NoSuchElementException if the option was None.
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用一些Ok-ok方法
val yourIntOrDefaultMinusOne = yourMap.getOrElse( "someKey", -1 )
Run Code Online (Sandbox Code Playgroud)