IntelliJ Worksheet中main方法无法运行问题咨询
Let's break down why your code isn't producing the expected output and how to fix it.
First, here's your code formatted for readability:
object Timer { // this function takes another function as an argument. // that function takes no args, and doesn't return anything. def oncePerSecond(callback: () => Unit) { while (true) { callback(); Thread.sleep(1000) } } // the function we'll pass in to oncePerSecond. // this can be any function that takes no args and doesn't // return anything. def timeFlies() { println("time flies like an arrow ...") } // the main() method, where we pass timeFlies into oncePerSecond. def main(args: Array[String]): Unit = { oncePerSecond(timeFlies) } }
The Root Cause
IntelliJ's Scala Worksheet uses an interactive execution model—it evaluates top-level definitions and expressions line by line, but it doesn't automatically detect or run main methods like a regular Scala application would. Your main method is defined inside the Timer object, but nothing in the worksheet is actually triggering it to run.
How to Fix It
The simplest fix is to explicitly call the main method at the top level of your worksheet, outside the Timer object. Here's the adjusted code:
object Timer { def oncePerSecond(callback: () => Unit) { while (true) { callback(); Thread.sleep(1000) } } def timeFlies() { println("time flies like an arrow ...") } def main(args: Array[String]): Unit = { oncePerSecond(timeFlies) } } // Explicitly trigger the main method to start execution Timer.main(Array.empty[String])
When you run the worksheet now, it will execute the final line, which calls Timer.main and starts your timer loop—you'll see the expected "time flies like an arrow ..." output printed every second.
A quick heads-up: since your code uses an infinite while(true) loop, you'll need to manually stop the worksheet execution in IntelliJ once you're done (look for the stop button in the worksheet's run toolbar).
内容的提问来源于stack exchange,提问作者Jwan622

