functional-programmingdataweavemulesoft

What's the output of `max`


This expression

max([1]) + 1

gives

Unable to call: `+` with arguments: (`1 | Null`, `1`).
 Reasons:
    - Expecting Type: `Number`, but got: `Null`.
        |-- From: `Number`  
        |- From: +(lhs: Number, rhs: Number) -> Number      
            50| max([1]) + 1
                ^^^^^^^^
    - Expecting Type: `Array<T>`, but got: `Null`.
        |-- From: `Array<T>`    
        |- From: +<T, E>(lhs: Array<T>, rhs: E) -> Array<T | E>     
            50| max([1]) + 1
                ^^^^^^^^
    - 10 more options ...

50| max([1]) + 1
    ^^^^^^^^^^^^

But typeOf(max([1])) gives Number. How to get the result of max as a Number that can be used in a number operation?


Solution

  • Looking at the documentation the return type of the max() function is T | Null, which is an union type:

    max<T <: Comparable>(@StreamCapable values: Array): T | Null

    Returns the highest Comparable value in an array.

    The items must be of the same type, or the function throws an error. The function returns null if the array is empty.

    The addition operator (+) is expecting Numbers as both arguments, not that one of them is an union type.

    To use the result of max() you should ensure that it can not actually be null. One way to do that is to convert the result to Number. A Null can not be converted to Number so be aware that it will fail if the list is empty.

    Example:

    max([1]) as Number + 1