I am creating demo code in Kotlin. I am trying so students should be able:
run function itself
run test
For example:
If function is created in .kt file, outside of class:
fun main(){
print("Hello world!")
}
it can be run
but I could not find the way to call it from the test
If the function is inside the class:
class Hello {
fun main(){
print("Hello world!")
}
}
the function can be called from the test
but can not be run - the green "Run" button is not visible.
Question: How to make such a function can be run manually and by test at the same time?
I'll assume you are writing your tests in Java, because if it's in Kotlin, calling main is trivial: main(), provided that you have imported the package/in the same package.
Kotlin global functions are compiled into static methods of a class with a name similar to the Kotlin file in which the function is declared, suffixed with Kt For example, if the file is called "app.kt", the class name would be AppKt. So if you declared main in app.kt, you would call:
AppKt.main();
in Java
You can change this name by annotating the Kotlin file with #JvmName:
#file:JvmName("MyOwnName")
Then you can call:
MyOwnName.main();
in Java.
See more documentation here
Related
I'm using kotlin compiler to analyze kotlin source file and I need to get where the method is defined using KtCallExpression.
KtCallExpression in question is retrieved from method call.
For better explanation, here's example, if there's source file named Main.kt with contents:
fun main() {
f1()
Test.f2()
}
fun f1() {
}
class Test {
companion object {
fun f2() {
}
}
}
when analyzing function main, it will produce 2 KtCallExpression, one for f1() and other for f2()
However I'm not sure how to get file Main.kt from KtCallExpression for f1(), or class Test from KtCallExpression for f2()
I tried to look for its documentations, however Kotlin compiler doesn't contain enough docs. I've also tried bunch of auto completion suggested by Intellij Idea but none of those doesn't seem to lead me to original declaration.
If I have app.kt file in kotlin, can I create instance like appKt()? Thanks.
Kotlin has top level function. For example I can write in app.kt:
val a = 123
fun abc() {}
appKt.abc()
my question is if I can create appKt instance and call instance method
Only classes can be instanced.
Instead of loose function fun abc() {}, this should be the method of a class:
class appKt() {
// private var a: Integer = 123
fun abc() {}
}
No, you can't put arbitrary code at the top level.
You can put only definitions of classes (just as in Java), objects, functions, and properties.
It wouldn't make much sense to put loose code there, anyway: when would it run?
It's not clear what you're trying to achieve with this. If you want some code that gets run when your program starts up, then you could put it into a top-level function — but you'd then have to call that function (e.g. from your main() method). Or you could put it in the init block of the companion object to a class that you know will be loaded. Or if you're using a framework such as Android or Spring, then that will probably provide ways to specify code to be run at start-up.
I am calling a function in a class S3FileOperationsAdapter from the main function in my kotlin code. I am injecting the class S3FileOperationsAdapter in the main function file. So it looks like
class Runner {
#set:Inject
lateinit var s3FileOperationsAdapter: S3FileOperationsAdapter
fun main(args: Array<String>) {
s3FileOperationsAdapter.readFunction()
}
}
Now the issue is:
When I try to run the above code, I get the error Error: Main method is not static in class com.amazon.bram.sim.BatchJobRunner, please define the main method as:. This is understandable.
And we can only make a static function within an object in kotlin. So upon doing that, I cannot Inject the dependency, because Dagger does not support injection into Kotlin objects. So it feels like a deadlock.
My question is, I want to inject the dependency in this file anyhow so that I can call the respective function. And I am calling this function from the "fun main()" in kotlin. How can I achieve this? Has anyone ever faced this before?
In order to inject anything in Dagger, you must first create an instance of your component. Since no code at all will run before fun main(), this needs to be done during main itself (or in a field initializer).
After creating an instance of the component, you can ask it for an instance of S3FileOperationsAdapter directly.
fun main(args: Array<String>) {
// Create the component.
val component = DaggerMyComponent.create()
// or use the Component.Builder or Component.Factory you defined for MyComponent.
// Get an object from the component.
// This method should be defined in your component interface.
val adapter = component.s3FileOperationsAdapter()
// Use the object.
adapter.readFunction()
}
If your actual code is more complicated, with multiple injected objects and a longer main() function, this may be a bit unwieldy. In that case, you can extract your current main() into its own class and let Dagger provide that class in main().
Currently, I'm creating a function, which is available for the dependencies block in Groovy with:
project.dependencies.ext.foo = { String value ->
project.files(extension.getFooDependency(project).jarFiles).asFileTree
}
Thanks to that, I'm able to do:
afterEvaluate {
dependencies {
compileOnly foo('junit')
}
}
I'm converting the Groovy code to Kotlin, and I'm wondering how to rewrite this foo extension.
I've ended up with:
project.dependencies.extensions.extraProperties.set("foo", Action { value: String ->
project.files(extension.getIdeaDependency(project).jarFiles).asFileTree
})
After calling foo('junit'), I get the following exception:
> Could not find method foo() for arguments [junit] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
I do not think that would work the same way in Kotlin DSL. Instead, you may declare a Kotlin extension function somewhere in the project. Then calling it would include all necessary receivers to you.
For multiple projects, I would recommend using a buildSrc project. Declarations there are visible to all project files below.
Speaking about Groovy and Kotlin support, I would do something like that:
private fun getFooImpl(scope: getFooImpl, name: String) { /*here is the implementation */ }
fun DependencyHandlerScope.getFoo(name:String) = getFooImpl(this, name)
//in Groovy
project.dependencies.extensions.extraProperties.set("foo", {getFooImpl(..)})
The same code could fit into a plugin as well. A more generic way could be to register a custom DLS extension, so to allow a custom block-like thisIsMyPlugin { .. } in the Gradle DSL and define all necessary helper functions in the extension class. Here the downside is in forcing users to wrap their code into the thisIsMyPlugin block.
I am having trouble with using internal kotlin functions in my Spock tests. Here's short snippet of my spock test:
private def preconditions = new MonetaryPreconditions()
private def usdMonetary = new Monetary(BigDecimal.ZERO, Currency.USD)
def "should throw nothing because Monetaries currencies are same"(){
when:
preconditions.checkMonetariesCurrencies(usdMonetary , usdMonetary )
then:
noExceptionThrown()
}
and my MonetaryPreconditions class:
internal object MonetaryPreconditions {
internal fun checkMonetariesCurrencies(monetary1: Monetary, monetary2: Monetary) {
if (monetary1.currency != monetary2.currency) {
throw CurrencyMismatchException(arrayOf(monetary1.currency, monetary2.currency), "Compared currencies does not match: " + monetary1.currency
+ " , " + monetary2.currency)
}
}
}
My test fails with a stacktrace:
groovy.lang.MissingMethodException: No signature of method: touk.recruitment.parkandrest.parkingmanagement.core.monetary.MonetaryPreconditions.checkMonetariesCurrencies() is applicable for argument types: (touk.recruitment.parkandrest.parkingmanagement.core.monetary.Monetary, touk.recruitment.parkandrest.parkingmanagement.core.monetary.Monetary) values: [touk.recruitment.parkandrest.parkingmanagement.core.monetary.Monetary#7c417213, ...]
The problem lies in internal visibility of my checkMonetariesCurrencies function. If I change it to public it works just fine, however I do want this to be module private. How can I achieve that with Spock?
Other information about my project:
Test class and MonetaryPreconditions have same package.
I am using Maven.
Test class and MonetaryPreconditions are of course in the same module.
I just ran into the same issue, and the workaround I used (suggested by an experienced coworker of mine) was to write a wrapper class in Kotlin (in the same package as the class under test (CUT); I placed the source code file in the test/kotlin folder) and just forward function calls to the CUT. I then used the wrapper class in my groovy unit test code.
Further, calling functions defined within an object in Kotlin from another programming language requires you to access the object's INSTANCE variable, e.g.
MonetaryPreconditions.INSTANCE.myfunction
In your case, the wrapper may look as follows:
package com.yourpackage
object MonetaryPreconditionsWrapper{
fun checkMonetariesCurrencies(monetary1: Monetary, monetary2: Monetary){
MonetaryPreconditions.checkMonetariesCurrencies(monetary1, monetary2)
}
}
Now you can test the MonetaryPreconditions.checkMonetariesCurrencies function by simply calling the wrapper function from the groovy code as follows:
MonetaryPreconditionsWrapper.INSTANCE.checkMonetariesCurrencies(monetary1, monetary2)
Thanks you Giuseppe for your answer. However for me, Spock didn't see the wrapper as it thought it was a property of the test class and threw a groovy.lang.MissingPropertyException. I had add this to build.gradle:
compileTestGroovy.classpath += files(compileTestKotlin.destinationDir)
Taken from here: https://localcoder.org/test-classes-in-groovy-dont-see-test-classes-in-kotlin