Skip to content

Instantly share code, notes, and snippets.

@danybony
Last active December 23, 2019 09:21
Show Gist options
  • Save danybony/0588277417ff521bbb355550ab7618af to your computer and use it in GitHub Desktop.
Save danybony/0588277417ff521bbb355550ab7618af to your computer and use it in GitHub Desktop.
Kotlin script and kscript

Collection of kotlin script and kscript examples

println("Called with args:")
args.forEach {
println("- $it")
}
// ----------------------------------------------------
// $ kotlinc -script helloScript.kts hello ‘with spaces’
//
// Called with args:
// - hello
// - with spaces
#!/usr/bin/env kscript
@file:MavenRepository("central", "https://repo.maven.apache.org/maven2/")
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2")
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core-common:1.3.2")
import kotlinx.coroutines.*
println("Start")
// Start a coroutine
GlobalScope.launch {
delay(1000)
println("Stop")
}
println("Hello")
Thread.sleep(2000)
//DEPS com.drewnoakes:metadata-extractor:2.12.0
import com.drew.imaging.ImageMetadataReader
import com.drew.metadata.Metadata
import java.io.File
val metadata: Metadata = ImageMetadataReader.readMetadata(File("image.jpg"))
import java.io.File
val folders: Array<File>? = File(".").listFiles { file -> file.isDirectory }
folders?.forEach {
folder -> println(folder.absolutePath)
}
// ----------------------------------------------------
// $ kotlinc -script dirsExplore.kts
//
// ./dir2
// ./dir1
import java.io.File
fun printCurrentAndSubdirs(currentDir: File) {
println(currentDir.path)
currentDir.listFiles { file -> file.isDirectory }?.forEach {
printCurrentAndSubdirs(it)
}
}
printCurrentAndSubdirs(File("."))
// ----------------------------------------------------
import java.io.File
fun File.printPathAndSubdirs() {
println(path)
listFiles { file -> file.isDirectory }?.forEach {
it.printPathAndSubdirs()
}
}
File(".").printPathAndSubdirs()
// ----------------------------------------------------
// $ kotlinc -script dirsExploreRecursionExtension.kts
//
// .
// ./dir2
// ./dir2/dir2.1
// ./dir2/dir2.2
// ./dir1
//INCLUDE utils.kt
@file:Include("util.kt")
val shouted = "hello!".upperCase()
#!/usr/bin/env kscript
println("Hello from Kotlin!")
for (arg in args) {
println("arg: $arg")
}
// ----------------------------------------------------
// $ chmod +x interpreter.kts
// $ ./interpreter.kts world
//
// Hello!
// arg: world
println("Hello from kscript")
println("The arguments were:")
args.forEach {
println("- $it")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment