You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IntelliJ Worksheet中main方法无法运行问题咨询

Why Isn't My Scala main Method Running in IntelliJ Worksheet?

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:31:15