2

I recently became aware of a generics-like notation to denote polymorphic types in DW 2.0.

The example below

%dw 2.0
output application/dw

fun id1(a) = a
fun id2(a: Any) = a
fun id3<T>(a: T) = a
var id4 = <T>(a: T) -> a
---
{
    "d1": id1,
    "d2": id2,
    "d3": id3,
    "d4": id4,
    r1: id1(10),
    r2: id2(10),
    r3: id3(10),
    r4: id4(10)
}

Illustrates that the signatures and the semantics of these functions are the same.

Which begs the question what is the difference between these definitions if any? Which one would you recommend?

Finally, confirm my assumption that DW 2.0 borrowed this generics-like syntax found in OO languages to support explicit polymorphic types.

NOTE: I did use application/dw in order to see the sigs of the functions while running the Preview from Anypoint Studio

TIA!

George
  • 2,758
  • 12
  • 16

1 Answers1

6

One of the most common uses for parametric polymorphism in DataWeave is to reflect in the type system functions where their return type depends on its input.

This is useful to avoid having to create specialized functions for each possible input type when the implementation will be the same and they will only differ in their signatures.

Note that this feature is only relevant during type-checking, this information is not carried during runtime.

In your example:

  • id1 will infer both the type of a from the usage of the id1 function and will also infer the return type because they were not specified.
  • id2 will infer that the return type is of type Any
  • id3 and id4 are the same, the return and a's type will depend on what you call the function with.

To exemplify the difference between Any and T you could try:

// var fails: String = id2("foo")
var ok: String = id3("foo")

Since the result of id2 can't be assigned to a String since it's Any, but id3 returns a String because it was given a String as input.

Shoki
  • 1,508
  • 8
  • 13