运行 REPL(交互式解释器)
我们可以运行如下命令得到一个可交互的 shell,然后输入任何有效的 Kotlin 代码,并立即看到结果
Kotlin 使用命令行执行 kts 脚本
Kotlin 也可以作为一个脚本语言使用,文件后缀名为 .kts 。
例如我们创建一个名为 list_folders.kts,代码如下:
import java.io.File
val folders = File(args[0]).listFiles { file -> file.isDirectory() }
folders?.forEach { folder -> println(folder) }
执行时通过 -script 选项设置相应的脚本文件。
$ kotlinc -script list_folders.kts <path_to_folder>
参考文章:
Note that script files support in Kotlin is still pretty much experimental. This is an undocumented feature which we're still in the process of designing. What's working today may change, break or disappear tomorrow.
That said, currently there are two ways to invoke a script. You can use the command line compiler:
kotlinc -script foo.kts <args>
Or you can invoke the script directly from IntelliJ IDEA, by right-clicking in the editor or in the project view on a .kts file and selecting "Run ...":