How to run a Scala script within IntelliJ IDEA?

前端 未结 4 1976
野的像风
野的像风 2021-02-05 02:05

Here is a trivial scala script:

object test {
  def hi() { print(\"hi there from here\") }
}


test.hi()

From the command line it does the expe

相关标签:
4条回答
  • 2021-02-05 02:47

    What works for me, is:

    1. Write a Scala script, e.g. MyScript.scala
    2. In the menu select: Run -> Edit Configurations...
    3. Press the "+" (⌘N also works on the Mac in this dialog)
    4. Select "Scala Script"
    5. Then select your Script file in this dialog enter image description here

    Now you can run your script. It's a bit inconvenient, but it works.

    Note: This works for me in IntelliJ IDEA 14.x

    0 讨论(0)
  • 2021-02-05 02:54

    Your code works in command line because it is "script", when you want to make it runnable in project there are ways to do it:

    1. By creating object which extends App

      object test {
          def hi() { print("hi there from here") }
      }
      
      object runnable extends App {
          test.hi()
      }
      
    2. or java-like solution i.e. creating main method

      object test {
          def hi() { print("hi there from here") }
      }
      
      object runnable {
          def main(args: Array[String]) {
              test.hi()
          }
      }
      
    3. when need to execute as script - I do it like that: select code to execute by mouse, then choose from context menu "Send Selection To Scala Console"

    0 讨论(0)
  • 2021-02-05 02:56

    There are 2 things to understand first. Scala works as both interpreter and compiler. You are trying to with interpreter "scala test.scala" without using "scalac test.scala" and interpreter works without main method also.

    Other way you can do in intellij is open the terminal or command prompt in intellij and run scala test.scala from the file location (Pre-requisite is scala in present the system path)

    0 讨论(0)
  • 2021-02-05 02:59

    The answer here is a combination of items:

    • (a) create a brand new Scala project (as suggested by @lhuang) and
    • (b) when running a script, you need to go into the Run Configuration and remove the Make step (as mentioned in the 'related' SOF question).

    This shows rough edges with Intellij and its scala plugin. Especially when I want to integrate scala with java it is apparently difficult if even possible using Intellij at this time (need to create new Scala project on a frequent basis is a non-starter for mostly java projects attempting to incorporate scala).

    But for scala-first projects it seems this may be workable.

    0 讨论(0)
提交回复
热议问题