0

I have defined a DataWeave function that takes a string as input and can handle null input as well. However, when I call it with null input, I encounter a syntax error. Could anyone tell me why? Thanks in advance

code

%dw 2.0
output application/json

fun convertToISO(dateString: String): String =
    if (dateString == null or !(dateString contains "Date")) 
        "" 
    else 
        do {
            var milliseconds = (dateString[6 to -3] as Number)
            ---
            milliseconds as DateTime {unit: "milliseconds"} as String
        }

---

{
    
        testCorrect: convertToISO("/Date(1716249600000)/"),
        testWrongEmpty : convertToISO(""),

       testWrongNull : convertToISO(null)
    
   
}

Error enter image description here

1
  • 1
    Do not use images for errors. Copy the text in the question using code block format. Commented Dec 3, 2024 at 11:38

1 Answer 1

1

The error message is telling you that null, which is of type Null, is not a compatible value for a String. You can remove the null check in that function because it is going to fail trying to pass it a null argument.

As alternatives you could do one of these:

  • Add a Union type to the parameter. Example: fun convertToISO(dateString: String | Null): String

  • Use a separate overloaded function for the null case. Example: fun convertToISO(dateString: Null): String = ""

  • Remove the null from the caller. This means ensuring that the function is never called with a null value as an argument.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.