Other [B4X] GetIfExists for Map [Map.Get already does this]

LWGShane

Well-Known Member
Licensed User
Longtime User
Here's a little piece of code that allows you to get a Key from the provided map. If the map doesn't contain the key then it'll return null.
B4X:
Private Sub GetIfExists (SourceMap As Map, Key As Object) As Object
    If SourceMap.ContainsKey(Key) Then
        Return SourceMap.Get(Key)
    Else
        Return Null
    End If
End Sub

This is perfect to use with single line declares:
B4X:
Dim SomeValue As String = GetIfExists(SomeMap, TheKey)
 

stevel05

Expert
Licensed User
Longtime User
That is exactly what map does. If the key doesn't exist, Null is returned.

You can also use GetDefault(Key,"Default") to return a default value of the correct type if the key doesn't exist.
 
Upvote 0

LWGShane

Well-Known Member
Licensed User
Longtime User
@stevel05
@Erel

You learn something new everyday; I didn't realize that the Get() method already did this primarily because the documentation doesn't state this.
 
Upvote 0
Top