Sunday 27 June 2021

How to create a new function in Pega

 Hi Friends, In this post we will see how to create a new function inside Pega and how to use it by expression builder.


Why we use function on my own way:

Assume a block of java code, which we are using in multiple places in our application. Instead of writing it in multiple places again and again, we can write that java code in a function so that we can reuse that function in our application wherever we need.

Writing a function in Pega is very easy to do. Lets see how to do that.


Below is the java code to get the reverse of a number. We will see how to create this as a function in pega.

class Main {
  public static void main(String[] args) {

    int num = 1234, reversed = 0;

    // run loop until num becomes 0
    while(num != 0) {
    
      // get last digit from num
      int digit = num % 10;
      reversed = reversed * 10 + digit;

      // remove the last digit from num
      num /= 10;
    }

    System.out.println("Reversed Number: " + reversed);
  }
}


First of all we have to create a library, If we are having already a library we can use that. In our case we will create a new library and use it.


So why we have to create library, In library we can keep the java packages so that we can reuse this packages in all the function creating with this library.


Creating a library with a name

Go to Rule Explorer -> Technical -> Library -> Create New


In Library rule, we can provide any package and static variable if  we needs inside the function rule

Note: Any packages or variable provided here is accessible inside function rule.



After creating library We will create a function rule named "ReverseNumber"

Create Function


Modify the java code to use in Pega function. Output will be returned in the variable "Reversed"

Created new funciton

Set output variable data type

Function output

Enable Function ready to be compiled check box once we have modified the code changes. Lets compile the java code to check whether we made any mistakes.


So lets check the code, In activity , by using expression builder selected the function created and provide the input value inside the bracket.

Select function from expression builder

Save the activity rule and run it. Input value provided is 123456789


Lets trace the activity and view the result.

Output
In tracer , we can view the number was reversed.

If you have any doubts , please ask in comment. Thank you Friends.



4 comments:

  1. it is very helpful thanks a lot

    ReplyDelete
  2. very Informative. it would be helpful if you also explain how to write a pega compatible java code

    ReplyDelete
  3. really useful.. excellent article

    ReplyDelete