Package-level functions

Programmers with a Java background are familiar with static methods. Static methods are declared within a class and can be accessed directly by using class names as a reference. Kotlin does not have a static method, but it does provide a package-level function instead. To create a package-level function, do the following:

  1. Create a package.
  2. Create a file in the package.
  3. Create a function in the file.
  4. In the project explorer, select a folder where we want to add a package and then right-click New followed by Package
  5. In the newly opened window, add a package name, for example, the Util package. 
  6. Once the Util package (folder) is created, right-click on package and add the Kotlin file. Call this file MyUtil. Our Kotlin file is now ready to have package-level functions added to it. 

Now open the MyUtil.kt file. We should see the following line here:

package Util

A directory or folder is called a package, which is where the Kotlin file resides. The package name is used as a reference to access the function. Let's create a function with a greeting message as follows:

package Util
fun hello() = println("Hello from Package Util")

The package-level function hello() has now been created and can be accessed by using the package name as follows:

PackageName.FunctionName()

Let's create the MyUtil package and add the MyTestUtil.kt file:

  1. Now open the MyTestUtil.kt file, add a main function, and call a package-level function, hello, to the file. A package-level function is always called using the package name as a reference:
fun main(args: Array<String>) {
Util.hello()
}
  1. Execute the program and verify the output, Hello from Package UtilAdd different functions under the Util package as follows:
fun hello() = println("Hello from Package Util")

val PI = 3.1415926535 // Package level variable

// Calculate power of given number
fun myPow(base : Double, exp: Double) : Double {
var result = 1.0
var counter = exp
while (counter > 0) {
result*= base
counter--
}
return result
}

// Calculate area of a circle
fun areaOfCircle(radius : Double) : Double{
return PI * 2 * radius
}

// Generate random number within given range
fun myRandom(range: IntRange) : Int{
return range.shuffled().last()
}
  1. Call these functions in the main function and verify the result as follows:
fun main(args: Array<String>) {

Util.hello()

println("Power Function")
println(Util.myPow(5.0,3.0))

println("Random number generator")
var range = 1..50
for (i in 1..5) {
println(Util.myRandom(range))
}

println("value of PI is ${Util.PI}" )
println("Area of circle " + Util.areaOfCircle(4.0))
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.82.154