IntelliJ IDEA and Scala tutorial

来源:互联网 发布:c3p0连接池配置优化 编辑:程序博客网 时间:2024/05/01 17:02

下面是完整的利用IntelliJ进行Scala开发的教程,摘自Cousera的Scala公开课,网址如下:

https://www.coursera.org/learn/progfun1/home/welcome

参考资料

http://www.scala-sbt.org/release/docs/Setup.html


第一步:要安装JDK,程序猿都知道!

Installing the JDK

Linux

  • Ubuntu, Debian: To install the JDK using apt-get, execute the following command in a terminal sudo apt-get install openjdk-8-jdk
  • Fedora, Oracle, Red Had: To install the JDK using yum, execute the following command in a terminal su -c "yum install java-1.8.0-openjdk-devel"
  • Manual Installation: To install the JDK manually on a Linux system, follow these steps:
  1. Download the .tar.gz archive from the Oracle website

2. Unpack the downloaded archive to a directory of your choice

3. Add the bin/ directory of the extracted JDK to the PATH environment variable. Open the file ~/.bashrc in an editor (create it if it doesn't exist) and add the following line:

1
export PATH="/PATH/TO/YOUR/jdk1.8.0-VERSION/bin:$PATH"

If you are using another shell, add that line in the corresponding configuration file (e.g. ~/.zshrc for zsh).

Verify your setup: Open a new terminal (to apply the changed ~/.bashrc in case you did the manual installation) and type java -version. If you have problems installing the JDK, ask for help on the forums.

接着安装一下sbt

Installing sbt


Installing from a universal package 

Download ZIP or TGZ package and expand it.

Ubuntu and other Debian-based distributions 

DEB package is officially supported by sbt.

Ubuntu and other Debian-based distributions use the DEB format, but usually you don’t install your software from a local DEB file. Instead they come with package managers both for the command line (e.g.apt-getaptitude) or with a graphical user interface (e.g. Synaptic). Run the following from the terminal to install sbt (You’ll need superuser privileges to do so, hence the sudo).

echo "deb https://dl.bintray.com/sbt/debian /" | sudo tee -a /etc/apt/sources.list.d/sbt.listsudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 642AC823sudo apt-get updatesudo apt-get install sbt

Package managers will check a number of configured repositories for packages to offer for installation. sbt binaries are published to Bintray, and conveniently Bintray provides an APT repository. You just have to add the repository to the places your package manager will check.

Once sbt is installed, you’ll be able to manage the package in aptitude or Synaptic after you updated their package cache. You should also be able to see the added repository at the bottom of the list in System Settings -> Software & Updates -> Other Software:

Ubuntu Software & Updates Screenshot

Red Hat Enterprise Linux and other RPM-based distributions 

RPM package is officially supported by sbt.

Red Hat Enterprise Linux and other RPM-based distributions use the RPM format. Run the following from the terminal to install sbt (You’ll need superuser privileges to do so, hence the sudo).

curl https://bintray.com/sbt/rpm/rpm | sudo tee /etc/yum.repos.d/bintray-sbt-rpm.reposudo yum install sbt

sbt binaries are published to Bintray, and conveniently Bintray provides an RPM repository. You just have to add the repository to the places your package manager will check.


IntelliJ IDEA Tutorial

1. Download IntelliJ IDEA Community Edition

IntelliJ IDEA Community Edition is an open-source version of IntelliJ IDEA, a premier IDE for Java, Scala and other JVM-based programming languages. You can download it from the official website.

2. Install the Scala plugin

When starting Intellij, a Welcome Screen shows up. The first step before creating or opening a Scala project is to install the Scala plugin. For that, go to the bottom right of the Welcome Screen and choose Configure → Plugins → Browse JetBrains Plugins. If such Welcome Screen doesn't appear, go to Preferences (Settings) → Plugins.

Note that Scala plugin requires restart to complete installation. Thus, restart Intellij before following the next steps.

3. Setup the JDK

From the welcome screen, go to Configure → Project defaults → Project structure and add the JDK. The JDK will be automatically detected, otherwise find the path where it's stored and select it from the file picker. More detailed instructions are here.

4. Creating a project

The easiest way to create a project is to use the Project Wizard. To use it, click Create New Project on the Welcome Screen, then select Scala, and finally SBT Project.


Click Next to specify project name and location. Once you've entered this information, IntelliJ IDEA will create an empty project containing a build.sbt file.

5. Creating a Scala worksheet

Simply use the Create New action from context menu or from a Scala package (anything under the `scala` folder).


To evaluate worksheets, use the corresponding toolbar icon (the play button), or press Alt+Ctrl+W (Alt+Cmd+W on OS X). In case of any problem, you can check the official documentation that thoroughly explains how to run the Scala Worksheet.

6. Creating a Scala class

Much akin to worksheets, Scala classes are created via context menu action Create New.

Once you are ready, run your application by pressing Ctrl+Shift+F10, or using the editor context menu.

After the application has finished running, you'll see its output in the Run tool window.

7. Opening an SBT project

To open an SBT project in IntelliJ IDEA, go to the Welcome Screen, click Import Project, and select SBT build file that you wish to open. IntelliJ IDEA will then create a new project and import the selected file to it.

Also, you can open an SBT project without calling the Import Project action. Just click Open Project from the Welcome Screen and select an SBT build file.

8. Synchronizing SBT and IntelliJ IDEA projects

IntelliJ IDEA SBT support synchronizes the project with your build file, so when you change Scala version you're going to use, or add a library, your project is updated accordingly. For the next time, you can avoid this step by checking off the option ''Use auto-import" in Step 7.

Note:the scalatest dependency has the scala version embedded in "scalatest_2.10" and that there's no `2.0` version for 2.11.x. So, replace:
1
libraryDependencies += "org.scalatest" % "scalatest_2.10" % "2.0" % "test"

by:

1
libraryDependencies += "org.scalatest" %% "scalatest" % "2.2.6" % "test"

The double percentage symbol will force sbt to use the current scala version defined in scalaVersion (which has to be "2.11.7" or "2.11.8").

9. Using terminal to run SBT commands

The easiest way to run SBT commands from from IntelliJ IDEA is to use the Terminal tool window via Alt+F12. It executes the terminal in your project directory. Then, type `sbt` to execute the build tool REPL. If you have any problem (your mappings are different, for instance), check the official documentation.

附一点内容:

SBT tasks

Starting up sbt

In order to start sbt, open a terminal ("Command Prompt" in Windows) and navigate to the directory of the assignment you are working on (where the build.sbt file is). Typing sbt will open the sbt command prompt.

1
# This is the shell of the operating systemshell$ cd /path/to/parprog-project
  -directory # This is the sbt shellshell$ sbt> _

SBT commands are executed inside the SBT shell. Don't try to execute them in the Scala REPL, because they won't work.

Running the Scala Interpreter inside SBT

The Scala interpreter is different than the SBT command line.

However, you can start the Scala interpreter inside sbt using the `console` task. The interpreter (also called REPL, for "read-eval-print loop") is useful for trying out snippets of Scala code. When the REPL is executed from SBT, all your code in the SBT project will also be loaded and you will be able to access it from the interpreter. That's why the Scala REPL can only start up if there are no compilation errors in your code.

In order to quit the interpreter and get back to sbt, type <Ctrl+D>.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
> console
[info] Starting scala interpreter...
Welcome to Scala version 2.11.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7
  .0_04-ea).
Type in expressions to have them evaluated.
Type :help for more information.
scala> println("Oh, hai!") # This is
  the Scala REPL, type some Scala code
Oh, hai!
scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> val squares = l.map(x => x * x)
squares: List[Int] = List(1, 4, 9)
scala> # Type [ctrl
  -d] to exit the Scala REPL
[success] Total time: 20 s, completed Mar 21, 2013 11:02:31 AM
> # We're back
  to the sbt shell

Compiling your Code

The compile task will compile the source code of the assignment which is located in the directory src/main/scala.

1
2
3
4
> compile
[info] Compiling 4 Scala sources to /Users/aleksandar/example/target/scala-2.11
  /classes...
[success] Total time: 1 s, completed Mar 21, 2013 11:04:46 PM
>

If the source code contains errors, the error messages from the compiler will be displayed.

Testing your Code

The directory src/test/scala contains unit tests for the project. In order to run these tests in sbt, you can use the test command.

1
2
3
4
5
6
7
8
9
10
11
12
> test
[info] ListsSuite:
[info] - one plus one is two
[info] - sum of a few numbers *** FAILED ***
[info] 3 did not equal 2 (ListsSuite.scala:23)
[info] - max of a few numbers
[error] Failed: : Total 3, Failed 1, Errors 0, Passed 2, Skipped 0
[error] Failed tests:
[error] example.ListsSuite
[error] {file:/Users/luc/example/}assignment/test:test: Tests unsuccessful
[error] Total time: 5 s, completed Aug 10, 2012 10:19:53 PM
>

Running your Code

If your project has an object with a main method (or an object extending the trait App), then you can run the code in sbt easily by typing run. In case sbt finds multiple main methods, it will ask you which one you'd like to execute.




0 0