https://kotlinlang.org logo
#library-development
Title
# library-development
z

zaleslaw

04/08/2021, 3:17 PM
Hi, I need some advice about examples and their usage in project infrastructure. I have 100 examples in the library that could be reused like integration tests for my library. Each example contains one main() function. I want to create 100 tests, each of them should call this main function. How to do it in Kotlin? How to call a specific main function? For example Example1.main()? It's easy in java, but I could not find a way in Kotlin.
i

Iaroslav Postovalov

04/08/2021, 3:29 PM
What's the problem with calling the function by its FQ name?
b

Big Chungus

04/08/2021, 3:36 PM
Import my.package.main as Main1 @Test fun test() { Main1() }
Main is just a top level function with specific reserved name and args spec. You can call it like any other top level function.
i

ilya.gorbunov

04/08/2021, 7:12 PM
The difference of
main
function is that it's allowed to have several top-level such functions in one package, but in different files. This works well when these functions are used as entry points for JVM, but it's impossible to distinguish them when calling from Kotlin
👍 1
So either you have to put each main in its own separate package and call it from Kotlin by fq-name or you can invoke them with Java reflection
z

zaleslaw

04/09/2021, 9:38 AM
The problem is that I don't want to pack each example in a separate package. As I see according @ilya.gorbunov the best way here to call them from Java because it could be distinguished there with FQ including the name of the file (converted to class) where it's located.
@Iaroslav Postovalov The problem is that FQ is not really FQ for the main functions. Unfortunately it doesn't include the underhood Java class name like (Example1Kt). Do you know how to write correct FQ if you have package with 10 examples and each of them has main entry point?
b

Big Chungus

04/09/2021, 9:41 AM
You can leave aliases in each file where main lives
fun main() {} val uniqueIdentifier = ::main
z

zaleslaw

04/09/2021, 9:42 AM
@Big Chungus sounds interesting, I wanted to avoid changes in examples for using in test infrastructure, but it could be a simple and enough clean solution, thanks
b

Big Chungus

04/09/2021, 9:45 AM
Or even better yet, have main delegate to named fun fun uniqueFunction() {} fun main() = uniqueFunction() Then use uniqueFunction in tests
z

zaleslaw

04/09/2021, 9:45 AM
Yeah, keep in mind this variant. But I was wondered that I have no ability to specify the road to main() call in Kotlin but I could do it in Java
b

Big Chungus

04/09/2021, 9:46 AM
Alternatively you could try object Wrapper { fun main(){} }
i

Iaroslav Postovalov

04/09/2021, 10:40 AM
Nope, @JvmStatic fun main looks much worse
e

ephemient

04/10/2021, 6:24 PM
@JvmName("main") fun uniqueMain()
?
z

zaleslaw

04/11/2021, 6:05 AM
Hmmmm, @ephemient sounds interesting