Skip to content

Commit 0bff46a

Browse files
imbanankoligee
authored andcommitted
Add composite script examples demonstrating .main.kts @file:Import functionality
1 parent 1da586c commit 0bff46a

File tree

4 files changed

+39
-0
lines changed

4 files changed

+39
-0
lines changed

jvm/main-kts/MainKts.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,5 @@ with easy interaction with Kotlin code and can be executed:
7272
```
7373
kotlin kotlin-shell.main.kts main-kts/example.txt
7474
```
75+
- [`composite/composite.main.kts`](scripts/composite/composite.main.kts) demonstrates script composition capabilities via `@file:Import` annotation
7576

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/usr/bin/env kotlin
2+
3+
/**
4+
* A script demonstrating the composition functionality of .main.kts scripts using imports.
5+
*
6+
* Key features:
7+
* - Supports both relative and absolute paths for imports
8+
* - Multiple imports using repeated annotations
9+
* - All public top-level declarations (variables, functions, classes) from imported scripts
10+
* become available in the importing script
11+
* - Each imported script is evaluated when imported, not just its declarations are included
12+
* - Imported scripts are evaluated in the order they appear
13+
*
14+
* Note: Import resolution is performed relative to the importing script's location
15+
* when using relative paths.
16+
*/
17+
18+
19+
@file:Import("kts/simple.kts")
20+
@file:Import("imported.main.kts")
21+
22+
sharedMainKtsVar++
23+
println("simple.kts members: $ktsScriptClassMembers")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
var sharedMainKtsVar = 2
2+
3+
// The __FILE__ variable contains the absolute path of the current .main.kts script
4+
println("Hi from $__FILE__")
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import kotlin.reflect.full.declaredMembers
2+
3+
// Kotlin scripts (.kts files) automatically include these dependencies:
4+
// 1. kotlin-script-runtime.jar - provides script-specific functionality
5+
val scriptArgs = args
6+
7+
// 2. kotlin-stdlib.jar - provides the Kotlin standard library
8+
println("Hello from simple.kts! Args=$scriptArgs")
9+
10+
// 3. kotlin-reflect.jar - provides reflection capabilities
11+
val ktsScriptClassMembers = this::class.declaredMembers

0 commit comments

Comments
 (0)