Kavindu Dodanduwa
Kavindu Dodanduwa

Reputation: 13059

Ballerina import from local package

I have a ballerina project structure as below

/  <- project root
|
 - my.foo <- first package
      |
       - FooFunctions.bal <- Some .bal file
|
 - my.bar <- second package
      |
       - BarFunctions.bal <- Another .bal file

Note how package namespaces are used. They have . in the middle. Now let's say I have following simple BarFunction.bal

public function someName() returns int {
  return 10;
}

How shall I refer and use someName from FooFunctions.bal ?

Upvotes: 0

Views: 799

Answers (3)

Natasha
Natasha

Reputation: 106

Since both 'my.foo' and 'my.bar' modules are from the same project, you don't need to provide the organization-name when defining the import statement.

According to your scenario if you want to use 'someName()' function which is in 'my.bar' module in 'my.foo' you can simply do the following in 'FooFunctions.bal':

import my.bar; 

public function main() {   
  // i will have the value returned from 'someName()' function
  int i = bar:someName(); 
}

Upvotes: 2

hYk
hYk

Reputation: 789

I presume that "BarFunctions.bal" and "BarFunction.bal" are the same. If so, you can import "my.foo" module to "BarFunctions.bal" bal file as below:

import my.foo;

You dont need the organization name of the module as they are from the same project.

Upvotes: 2

Kavindu Dodanduwa
Kavindu Dodanduwa

Reputation: 13059

Official docs on packaging can be found from this link.

In simple terms [as of Ballerina 0.982 version], you can import my.bar package inside my.foo packages's any .bal file like below,

import ballerina/io;
import <org-name>/my.bar;

public function main(string... args) {
    io:println(bar:someName());
}

Where you replace the <org-name> from your project's root level Ballerina.toml file's org-name value. And note how bar is used to refer functions coming from my.bar package. This is highlighted in Ballerina document as below,

Identifiers are either derived or explicit. The default identifier is either the package name, or if the package name has dots . include, then the last word after the last dot.

Furthermore, you may choose an identifier for package you import. For example, I can identify <org-name>/my.bar as barimport with following syntax,

import ballerina/io;
import <org-name>/my.bar as barimport;  # Now we refer import as barimport

public function main(string... args) {
    io:println(barimport:someName());
}

Upvotes: 2

Related Questions