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

Discussion in 'Android Questions' started by ShaneG30, May 26, 2018.

  1. ShaneG30

    ShaneG30 Well-Known Member Licensed 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.
    Private Sub GetIfExists (SourceMap As Map, Key As Object) As Object
    If SourceMap.ContainsKey(Key) Then
    Return SourceMap.Get(Key)
    Return Null
    End If
    End Sub
    This is perfect to use with single line declares:
    Dim SomeValue As String = GetIfExists(SomeMap, TheKey)
  2. stevel05

    stevel05 Expert Licensed 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.
  3. Erel

    Erel Administrator Staff Member Licensed User

    I moved it to the questions forum. As stevel05 explains there is no reason to use the code above.
    ShaneG30 likes this.
  4. ShaneG30

    ShaneG30 Well-Known Member Licensed User


    You learn something new everyday; I didn't realize that the Get() method already did this primarily because the documentation doesn't state this.
    Erel likes this.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice