Search code examples
powershelloption-type

Equivalent of "Optional" (maybe type) from Java in Powershell


Citing wikipedia:

In programming languages (especially functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; https://en.wikipedia.org/wiki/Option_type

Code from the method where I would like to put the Optional is:

function FindElement {

 if ($element -ne $null) {
        $valueFromXml =   $element.InnerText
        Write-Information "valueFromXml found in   xml: $valueFromXml "
        return  $valueFromXml

    } else {
        Write-Information "valueFromXml  not found."
        return null #I do not like to return null, need to refactor that
    }
}

I am using Optional<> Type in Java very often but I am not able to find anything like that in PowerShell. Is there any structure in Powershell which provides same functionality? How to use it in my code at lines:

 return  $valueFromXml

and

return null

And how to handle the return value after calling the method FindElement ?


Solution

  • UPDATE: replaced exit with return as of @mclayton's suggestion

    SCRIPT IMPROVEMENT

    function FindElement {
        [CmdletBinding()]
        param (
            $Element
        )
        process {
            # if null, writes it to the Information Stream and exits the function altogether
            if ($null -eq $Element) {
                Write-Information 'valueFromXml  not found.'
                return
            }
                
            # No need for `else`: it's never going to reach here unless $Element is not null
            $valueFromXml = $element.InnerText
            Write-Information "valueFromXml found in   xml: $valueFromXml "
            return  $valueFromXml
    
        }
    }
    

    --

    PS > $Var = FindElement -Element $null
    PS > $null -eq $Var
    True
    

    OLD ANSWER

    Sure, it's Nullable
    Usually powershell converts $Null assignments to whatever is the empty value default of the class of the variable. [int]$null returns 0 for example.

    But [System.Nullable[int]]$null returns $null