Lecture: Working With IntelliJ IDEA

For programmers who would like to use IntelliJ IDEA with this course.

You need IDEA 12 or IDEA 13 to work with the projects provided with this course. JetBrains offers a 30 day trial for IDEA Ultimate, but the free version should also work. You need Ultimate in order to work with Play. This lecture was originally produced with IDEA 12.1.3 and this transcript was updated to IDEA 13.1.1. If you have an older version of IDEA then some portions of this lecture will not correspond to what you see on your screen.

A word about the Scala compiler - scalac has been packaged many ways, and IDEA currently provides most of them. Regardless of how scalac is packaged, it needs a lot more memory than the Java compiler. In particular, large projects, or projects that use implicits heavily require more memory. The instructions below are intended to guide you through the most appropriate way of configuring the Scala compiler options. Some of the options currently available will be removed in the next major version of IDEA - this is good because the options that are being removed are not as effective as the newer options that have recently been added. The following instructions only discuss how to work with the Scala compiler configuration options that are expected to remain going forward. This lecture will be updated whenever configuration settings for Scala change with new releases of IDEA.

Configuring IDEA

Under Linux and Windows with Cygwin, you can launch IDEA like the following. Be sure that JAVA_HOME is set. Of course, the directory you installed into will likely be different:

/opt/idea-IU-129.161/bin/idea.sh &> /dev/null &

Under Mac:

/Applications/IntelliJ\ IDEA\ 13.app/Contents/MacOS/idea &

When IDEA starts for the first time, it will run the Initial Configuration Wizard, and ask for the plugins that you want to enable. I have not noticed issues with having lots of unnecessary plugins enabled, and you can disable plugins easily at any time, so you should press the Skip button and move on.

If you import a settings file (from the Welcome to IntelliJ IDEA screen: Configure / Import settings), by default called settings.jar, then all of the following settings could be set.

  1. When IDEA finally presents the Welcome panel, you will see an entry labeled Configure. Click on that button.
  2. On the Configure panel click on Plugins. This is where you can download and install the Scala and sbt plugins.
  3. If you are not using Play Framework 1.0 (and you should not!), disable the Playframework support plugin because that only works with Play Framework version 1.
  4. Click on the Install JetBrains plugin... button and scroll down.
  5. Highlight Scala plugin and right-click, so you see Download and Install. If you are using Play 2.0, also install the Play 2.0 Support plugin (from the JetBrains repository) and the Remote Call plugin (from the third party repository) and wait for the plugins to download. I do not recommend that you run plugin downloads in the background.
  6. Close the Browse Repositories window.
  7. Click OK.
  8. Allow IntelliJ IDEA to restart.
  9. Verify that the plugins were installed.
  10. If you are running Ubuntu Linux, click on Configure / Create Desktop Entry.
  11. You need to define a default project JDK before you can configure Scala. To do that:
    1. Click on Project Defaults / Project Structure / Project
    2. Click the New... button, then select JDK. Browse to your JDK. For Mac this will be a path like /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home. For Ubuntu Linux, this will be under /usr/lib/jvm.
    3. Click OK and then click on the back arrow.
  12. Configure / Project defaults / Project Structure is where you specify the default JDK and Java language level.
    1. I selected JDK 1.7 and language level 7.0 Diamonds, ARM, multi-catch, etc.. No need to specify anything else, just click OK.
  13. Back up to the Configure menu, and click on Preferences.
  14. You should now see a section on the left entitled Template Project Settings - these settings can also be applied to an opened project by selecting File / Project Structure from an open project.
    1. Compiler
      1. It is safest (but a bit slower) to enable Clear output directory on rebuild.
      2. You should enable Compile independent modules in parallel.
      3. The default Compiler process heap size (Mbytes) of 700MB is for non-Scala compilers. This memory is allocated on first use, so you can ignore this setting.
    2. Inspections
      1. I turn these warnings off:
        1. HTML / File reference problems (so Play templates do not have a lot of complaints over missing files)

        2. Scala / Method signature / Method with Unit result type defined like function

        3. Scala / Method signature / Method with Unit result type defined with equals sign

      2. I turned these warnings on:

        1. Scala / General / Relative import

    3. Scala
      1. Imports
        1. I set Class count to use import with '_': to 9999 because I like explicit imports.
        2. Set Add full qualified imports.
        3. Unset Import the shortest path for ambiguous references because that setting can get you into trouble when you optimize imports.
      2. Worksheet:
        1. Evaluation results length before line break: I set this to 120.
        2. Output cutoff limit: I set this to 100
      3. Other Settings
        1. Enable Highlight arguments to by-name parameters.
    4. Version Control: Unset Notify about VCS root errors
  15. IDE Settings
    1. Appearance:

      1. Enable Show line numbers

      2. Change the Theme to Darcula. IDEA will restart.

      3. If you are used to the Eclipse IDE's shortcut keys, you can use them with IDEA by setting them from File / Settings / Keymap. Select the predefined Eclipse key map. Unless you and your entire team are committed to programming exclusively on the Mac, I suggest you do not use the Eclipse Mac key bindings, because they do not map to Linux or Windows key bindings for Eclipse.

    2. Editor - uncheck Allow placement of caret after end of line.

      1. Appearance - enable Show method separators so horizontal lines are drawn between methods
      2. Colors & Fonts select Scheme name Darcula
      3. If your monitor has a 16:9 or 16:10 aspect ratio, you may want to maximize vertical dimension for your editor. In that case, set Editor Tab Appearance / Placement to Left or Right. You can also reclaim some vertical space by disabling the toolbar by right-clicking on it and deselecting Show Toolbar. You can re-enable the toolbar with the View / Toolbar menu item.
    3. Scala
      1. Enable Show type info on mouse motion with delay.
      2. You can select the incremental compiler setting of your choice; I use the default, which is IntelliJ IDEA. Here is some background.
      3. Enable Run compile server (in external build mode), which keeps the compiler 'warm' between compilations, thereby reducing the compile time.
      4. Make sure the JVM SDK points to a valid JDK.
      5. JVM maximum heap size, MB: This memory is used to convert the IDEA project model to something compatible with the Zinc server, and to parse error messages from the compiler. The lifespan of this memory allocation is only during a compilation, and should be increased to 1500 or 2000, depending on the size of your project.
  16. Click OK

  17. Back arrow, you now see the Configure menu

Tuning Memory Allocation

You can use jvisualvm, provided with the Java Development Kit, to measure memory usage of the IDE, so you can optimize the memory settings. The VisualVM site has many articles that discuss how to use the tool. I suggest that you do not use the VisualVM IDE plugin to measure the IDE that it runs from, and instead run the tool standalone!

In the IDEA installation directory, edit bin/idea.vmoptions. My development machine has 32 GB RAM, and I use that memory to run several virtual machines simultaneously. Each VM has 7 GB RAM. Here are my settings:

-Xms1128m
-Xmx2512m
-XX:MaxPermSize=500m
-XX:ReservedCodeCacheSize=164m
-XX:+UseCodeCacheFlushing
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true

Creating a Scala Project

Recommendation - do not follow this process to create a scala project from IDEA, instead create an sbt project (copy sbtTemplate to make your life easier) then convert it to IDEA using gen-idea, described next.

1) Start IntelliJ IDEA, and click on Create New Project.

2) Give your new project a name.

3) The project name will be used as the IntelliJ module name by default.
4) Click Finish and you will be presented with this query. Click OK.
5) After a moment the Project panel will open up. Click on the module name to open it. The top one or two directories are the .idea* directories; normally you should not need to look inside.

6) The src directory is automatically created for you. This directory contains your source code, including Java and Scala code, and can also include resources. To make a source file inside it, right-click on the src directory, select New and then Scala Class.

We select Scala Class even if we want to make a Scala object or a Scala case class.

7) Give your new Scala file a name. The Scala file will have a .scala file type automatically added.
8) IDEA creates a default Scala class with the name of the file.
9) We need a main method for our console application. This means we need to extend an object (not a class) with the App trait. Change the word class to object and add extends App. The constructor for the object consists of only one line, which prints the traditional Hello, world!
10) Let's run the console app by right-clicking on it in the Project panel and selecting Debug Weather.main().
11) You are notified that an external Scala compiler is being used to compile the program. This is good. While IDEA builds, you will see the status line at the bottom of the screen shows all the actions performed.
12) Output appears in the Debug panel which opens up at the bottom of the IDEA window. You can click on the Debug tab to show or hide the Debug panel. You can rerun the app by clicking on the little green bug on the left side of the Debug panel.
13) You can edit the debug configuration by clicking on the pull-down menu at the top center of the IDEA window.
14) You can add arguments for the JVM and your program, as well as tweak other settings.
15) If you enable Share, the debug configuration is written to a file in the .idea directory. You can check it into git if you want:
$ git add -fA .idea/runConfigurations/*
$ git commit -m "New run configuration"
$ git push
16) A completed program.

Opening SBT projects

IntelliJ 13 for Scala has some new options which are non-obvious. You can now open a build.sbt file instead of running sbt gen-idea, discussed in the next section. When you do so, you will see the following dialog box. You should always enable both options.

"Use auto-import" option turns on subsequent monitoring of relevant project configuration files (*.sbt, ./project/**) and project refreshing on changes in those files.

Create directories ... " checkbox can be used to automatically create source and test directories (like main/src/java/) that are reported by SBT but not yet present in a project (so that Project Structure / [Module] / Sources contained no red entries.

The JetBrains Scala team indicated to me that they will soon add the means to explicitly update projects. They also told me that the checkboxes will probably be removed from the project import dialog in a future release. To modify these settings afterwards, you may access them via Project Settings / SBT.

Converting SBT Projects Into IntelliJ Projects

This section discusses how to work with IntelliJ IDEA on Scala projects in a more traditional manner, instead of opening SBT projects directly. This might be required if you are using IDEA 12, or if you have a complex SBT setup.

At the command line, navigate to the course_scala_intro_code directory. It contains two directories, called courseNotes and assignment.

To export the courseNotes sbt project to IDEA, change to the courseNotes directory and run this command:

sbt gen-idea

If this is the first time you run sbt with this project, you will have to wait several minutes while many dependencies are downloaded. Eventually you will see something like:

[info] Loading global plugins from C:\Users\Mike Slinn\.sbt\plugins
[info] Loading project definition from C:\scalaCore\scalaIntro\courseNotes\project
[info] Set current project to scalaJavaOOCompatCourse (in build 
file:/C:/scalaCore/scalaIntro/courseNotes/)
[info] Trying to create an Idea module scalaJavaOOCompatCourse
[info] Excluding folder target
[info] Created C:\scalaCore\scalaIntro\courseNotes/.idea/IdeaProject.iml
[info] Created C:\scalaCore\scalaIntro\courseNotes\.idea
[info] Excluding folder C:\scalaCore\scalaIntro\courseNotes\target
[info] Created C:\scalaCore\scalaIntro\courseNotes\.idea_modules/scalaJavaOOCompatCourse.iml
[info] Created 
C:\scalaCore\scalaIntro\courseNotes\.idea_modules/scalaJavaOOCompatCourse-build.iml

Now change to the the assignment directory and run the same command:

sbt gen-idea

Again, output should look something like:

[info] Loading global plugins from C:\Users\Mike Slinn\.sbt\plugins
[info] Loading project definition from C:\scalaCore\scalaIntro\assignment\project
[info] Set current project to scalaIntroAssignment (in build 
file:/C:/scalaCore/scalaIntro/assignment/)
[info] Trying to create an Idea module scalaJavaOOCompatAssignment
[info] Excluding folder target
[info] Created C:\scalaCore\scalaIntro\assignment/.idea/IdeaProject.iml
[info] Created C:\scalaCore\scalaIntro\assignment\.idea
[info] Excluding folder C:\scalaCore\scalaIntro\assignment\target
[info] Created 
C:\scalaCore\scalaIntro\assignment\.idea_modules/scalaJavaOOCompatAssignment.iml
[info] Created 
C:\scalaCore\scalaIntro\assignment\.idea_modules/scalaJavaOOCompatAssignment-build.iml

The gen-idea command creates two directories, named .idea and .idea_modules. Both of these directories should be mentioned in the .gitignore file. You can examine the .gitignore files provided with the projects for this course.

Working With IDEA

  1. Start IDEA and click the Open Project menu item.
  2. Select the directory called courseNotes and click Choose.
  3. The Scala project should load into IDEA. We can now finish setting up IDEA. You will notice a small rotating icon at the bottom of the IDEA window, and the word Indexing... next to it. The first time IDEA encounters a new jar, such as found with a new JDK, it will index the jar. This can take a while, and the process might slow down your computer noticeably.
  4. Click the tiny rectangle at the lower left of the IDEA screen to open the Project panel
  5. Click on Project
  6. Double-click on the project name at the top of the Project pane to expand it. Also expand the src directory contents.
  7. The project directory contains the sbt project files and directories. The External libraries directory is presented to you by IDEA so you can browse the project dependencies. These files actually reside in ~/.ivy2. Note that there are two versions of the Scala compiler, one for the SBT build system and one to compile your code.

    We need to configure the project structure before we can compile. File / Project structure opens a new window, and the Project SDK is probably invalid. You need to tell IDEA where your JDK is, so click the New... button, select JDK and navigate to the directory that you installed the JDK. Click the Apply button at the lower right of the window. We are done with Project Settings.

  8. Select a runnable application, such as WordSearch, and right-click.
  9. Select Debug. If all goes well, the project will compile and run. However, there is a really good chance that this will fail. We'll tackle that right now.

Fixing the No 'scala-library*.jar' in Scala compiler library error

The problem is that the Library definition for the scala compiler is missing some or all of its contents. IDEA 13 is supposed to make this problem go away. Until then, here is what you need to do:

  1. Select the File / Project Structure menu item.
  2. Select the Libraries menu on the left. You will see three definitions, and one will be empty. Let's look at each definition in turn:
    1. scala-library (this is the Scala run-time library, and it consists of the executable jar, source code jar and Javadoc jar)
    2. scala 2.10.2 (this is the collection of jars for running the Scala compiler)
    3. scala 2.10.3 (empty!). This definition is the problem. Might as well delete it - that will make detecting where it is referenced easier. To do that, right-click on the entry and select Delete, then click OK.
    4. Now select the Modules item on the left, open the topmost project entry, and select Scala.
    5. Select the collection of jars for running the Scala compiler.
    6. Try debugging the project again. It should work this time!

Helpful Hints

You may find that the editor does not parse complex Scala code or Play templates properly. If this happens you will see lots of good code highlighted as errors on the screen, and cutting and pasting may work improperly. You can temporarily toggle the Scala for the editor parser off and on by clicking in the small [T] symbol at the bottom right of the screen, in the status bar area. When Scala parsing is disabled, the symbol displays as [_].

Worksheets

Scala worksheets are combination of a REPL with and IDE. They are very helpful since your project's classpath is provided to the worksheet. Check it out with File / New / Scala Worksheet.

Useful IntelliJ Hot Keys

If you have set up Eclipse keyboard shortcuts as described, the following extra keyboard shortcuts are specific to IntelliJ IDEA. The Key Promoter and Shortcut Keys List plugins are helpful for learning IntelliJ keyboard hot keys.

Shift Shift (twice in a row) - search everywhere, also shows recently edited files

Alt + 1 Toggle project view

Ctrl + E Open recently edited files

Ctrl + Shift + E Open recently changed files

Alt + Home Open navigation bar

Alt + = Shows the inferred type of the highlighted variable or expression.

Ctrl + hover Shows summary of all kinds of useful information about artifact under cursor.

Ctrl + Space Code completion.

Ctrl + Shift + Enter Correct syntax of code

Ctrl + B Rebuild project.

Ctrl + Shift + A Find Action (learn key bindings, or perform unbound actions)

Ctrl + Alt + V Create a variable from an expression.

Ctrl + Shift + B Toggle breakpoint on current line.

Ctrl + Shift + J Join lines.

Ctrl + Shift + V Paste from 5 most recent copies.

Hot Keys From Eclipse Key Bindings

The following are some of the keys defined when you enable Eclipse key bindings.

Ctrl + D Delete line.

Ctrl + E and Ctrl + Shift + E Show list of recent files.

Ctrl + F Highlight all occurrences of selected text, and optionally search in current directory.

Ctrl + H Find in project, or if a directory is highlighted in the project pane, restrict search to that subdirectory tree.

Ctrl + Alt + B Pop up list of overrides or implementations, or go to implementation if there is only one.

Ctrl + / Comment / uncomment current line (toggle).

Ctrl + Shift + / Comment / uncomment current selection (toggle).

F2 or Ctrl + Shift + Space Show type or method signature of method under cursor.

Ctrl + Shift + F Reformat file or selected code.

Alt + Shift + R Rename artifact under cursor.

Ctrl + Shift + R List matching files anywhere in project and optionally open one. Can also specify a filter.

Price Free
Signed up TODO