I am working on a project which involves Kotlin, Java, and Scala at the same time. In a scenario, I need to execute a Scala function from Kotlin. How can I do it?
The same way you normally execute functions in Kotlin.
Just compile Scala code to bytecode and add it to Kotlin classpath.
Example:
In folder <classpathFolder>
put:
ScaTest.scala
:
class ScaTest() {
import math._
def mathFunction(num: Int) = {
val numSquare = num*num
(cbrt(numSquare) + log(numSquare)).toInt
}
}
Compile with scalac ScaTest.scala
It should produce file ScaTest.class
In some other folder create Kotlin file:
KotTest.kt
:
fun main() {
val ss = ScaTest()
println(ss.mathFunction(4))
}
Compile with kotlinc -classpath <classpathFolder> KotTest.kt
This should produce file KotTestKt.class
Run with kotlin -classpath <classpathFolder> KotTestKt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.