運行 REPL(交互式解釋器)
我們可以運行如下命令得到一個可交互的 shell迅涮,然后輸入任何有效的 Kotlin 代碼蝎宇,并立即看到結(jié)果
Kotlin 使用命令行執(zhí)行 kts 腳本
Kotlin 也可以作為一個腳本語言使用,文件后綴名為 .kts 蟋软。
例如我們創(chuàng)建一個名為 list_folders.kts镶摘,代碼如下:
import java.io.File
val folders = File(args[0]).listFiles { file -> file.isDirectory() }
folders?.forEach { folder -> println(folder) }
執(zhí)行時通過 -script 選項設(shè)置相應(yīng)的腳本文件。
$ 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 ...":