Skip to content

Support Kotlin higher-order functions/lambdas #977

Open
@jsommr

Description

@jsommr

NativeScript supports marshalling Java bytecode generated by Kotlin. But Kotlin has a way to specify that a function takes another function in a much better way than Java.

Like this:

fun myfun(callback: (arg: String) -> Void)

It compiles to something like

public final void myfun(@org.jetbrains.annotations.NotNull final kotlin.jvm.functions.Function1<? super String, Void> callback)

where Function1 is a class containing an invoke method. Depending on how many args the function takes, it'll be called Function2, Function3 and so on.

Interacting with myfun from JavaScript would be done this way:

myfun(new kotlin.jvm.functions.Function1({ invoke: () => console.log("invoked") }))

It would be so cool if NativeScript supported Kotlin-functions out of the box, so the callback wouldn't need to be wrapped in FunctionX and myfun could be run via myfun(() => console.log("invoked")). This would make it easier to align with an Objective-C library, where blocks are supported.

To support Kotlin, my app.gradle currently looks like this:

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.30"
    }
}

dependencies {
  compile fileTree(dir: "libs", include: ["*.jar"])
  compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:1.2.30"
}

android {  
  defaultConfig {  
    generatedDensities = []
    applicationId = "org.nativescript.test"  
  }  
  aaptOptions {  
    additionalParameters "--no-version-vectors"  
  }  
} 

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions