Android Tutorial Creating a simple Kotlin wrapper library

The purpose of this tutorial is to show a way of compiling Kotlin into your developed library as a “fat” JAR (a JAR file containing all necessary dependencies and classes bundled in).

Compared to Java the programming language, Kotlin has additional powerful language features such as: Data Classes, Default Arguments, Extensions, Elvis Operator, and Destructuring Declarations.

Required tools:
Kotlinc
SimpleLibraryCompiler
Imagination

Here are a few example Kotlin functions:

B4X:
@file:JvmName("B4XUtils")


package demo
import java.util.Random;
class b4akotlin
val random = Random()

fun printsout() {
println("Hello Kotlin meet B4A!")
}

fun rand(from: Int, to: Int) : Int {
    return random.nextInt(to - from) + from
}

fun sum(a: IntArray): Int {
        var result=0
          for (number in a)
            result += number
        return result
    }

fun main(args: Array<String>) {
    println("Hello World!")
}

fun findPairless(a: IntArray) = a.fold(0, {accum, x -> accum xor x})

Compile the above into a Jar using kotlinc

B4X:
kotlinc hello.kt -include-runtime -d h:\path_to_project_lib\hello.jar


Now write a simple wrapper:

B4X:
package com.Kotlin;

import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.DependsOn;
import anywheresoftware.b4a.BA.ShortName;
import anywheresoftware.b4a.BA.Version;
import anywheresoftware.b4a.BA.Author;

@Version(1.8f)
@ShortName("Kotlin")
@DependsOn(values={"hello"})

public class Kotlin {
    public void consoleprintout() {
    new demo.b4akotlin();
    demo.B4XUtils.printsout();
}
    public int randomnumber(int x,int z) {
    new demo.b4akotlin();
    return demo.B4XUtils.rand(x , z);
}

    public static int summ(int[] a) {
    new demo.b4akotlin();
    return demo.B4XUtils.sum(a);
}

    public static int findpairs(int[] a) {
    new demo.b4akotlin();
    return demo.B4XUtils.findPairless(a);
}

}
 
Last edited:

Star-Dust

Expert
Licensed User
Longtime User
Interesting, but did you stop?

See also the @Moster guide in this thread
 

cxdzbl

Active Member
Licensed User
I need to use Kotlin to package a b4a Library Tutorial, preferably pictures and text tutorials, so that I can translate to learn.
 
Top