1. 程式人生 > >Scala - 02 - 搭建開發環境

Scala - 02 - 搭建開發環境

href scala安裝 搭建開發環境 before 編譯 pts 回車 ogr -a

1- 下載與安裝

下載鏈接:http://www.scala-lang.org/download/

CMD

To run Scala from the command-line, simply download the binaries and unpack the archive. http://www.scala-lang.org/download/install.html

CMD : SBT(Simple Build Tool)

專門為scala語言設計的構建工具,包括運行環境,能夠進行依賴管理、編譯、打包等工作。 下載安裝,重啟系統,確認Path 變量和Classpath 變量已正確設置後,在命令行下直接運行sbt命令即可。
  • http://www.scala-sbt.org/
  • http://www.scala-sbt.org/documentation.html
  • http://www.scala-lang.org/documentation/getting-started-sbt-track/getting-started-with-scala-and-sbt-on-the-command-line.html
  • http://www.scala-lang.org/documentation/getting-started-sbt-track/testing-scala-with-sbt-on-the-command-line.html

IDE:The Scala IDE (based on Eclipse)

  • http://scala-ide.org/
  • http://scala-ide.org/docs/
  • http://scala-ide.org/docs/tutorials/index.html
  • SDK(http://scala-ide.org/download/sdk.html),其實是為Scala定制的Eclipse版本(將Scala及插件集成到Eclipse),解壓後是一個直接可用的Eclipse。在Help---》Installation details可以查看已安裝的插件包。
  • Update site installation(http://scala-ide.org/download/current.html),對於已有Eclipse可以選擇插件方式安裝,但要註意版本匹配關系。

IDE:IntelliJ IDEA with the Scala plugin

  • https://www.jetbrains.com/idea/
  • https://www.jetbrains.com/help/idea/creating-and-running-your-scala-application.html
  • http://www.scala-lang.org/documentation/getting-started-intellij-track/getting-started-with-scala-in-intellij.html
  • http://www.scala-lang.org/documentation/getting-started-intellij-track/building-a-scala-project-with-intellij-and-sbt.html
  • http://www.scala-lang.org/documentation/getting-started-intellij-track/testing-scala-in-intellij-with-scalatest.html

參考信息

  • 利用IntelliJ IDEA與Maven開始你的Scala之旅:http://www.jianshu.com/p/ecc6eb298b8f
  • Scala + IntelliJ IDEA:http://www.cnblogs.com/wjcx-sqh/p/6551248.html

2- 在Windows系統安裝Scala

2.1- 確認已成功安裝配置Java環境

C:\Users\guowli>java -version
java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

C:\Users\guowli>javac -version
javac 1.8.0_101

2.2- 下載安裝Scala安裝包

下載鏈接:http://www.scala-lang.org/download/ 技術分享圖片 註意:一般情況下,msi版本會自動配置環境變量,zip版本需要手動配置環境變量。 為了避免莫名其妙的問題,建議使用zip版本手動配置並確認環境變量。

2.3- 設置環境變量

我的電腦---》屬性---》高級系統設置---》環境變量 新建 SCALA_HOME變量
  • 變量名:SCALA_HOME
  • 變量值:Scala的安裝目錄

技術分享圖片

設置 Path 變量 找到系統變量下的"Path",單擊編輯,添加路徑:“ %SCALA_HOME%\bin;”,註意後面的分號 不要漏掉。 設置 Classpath 變量 (也可能為CLASSPATH,不區分大小寫):找到找到系統變量下的"Classpath",單擊編輯,添加如下內容
;%SCALA_HOME%\bin;%SCALA_HOME%\lib\dt.jar;%SCALA_HOME%\lib\tools.jar.;
如果沒有,則單擊"新建":
  • "變量名":ClassPath
  • "變量值":.;%SCALA_HOME%\bin;%SCALA_HOME%\lib\dt.jar;%SCALA_HOME%\lib\tools.jar.;
註意:"變量值"最前面的 .; 不要漏掉。最後單擊確定即可。

2.4-驗證

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\guowli>scala -version
Scala code runner version 2.12.4 -- Copyright 2002-2017, LAMP/EPFL and Lightbend, Inc.

C:\Users\guowli>sclac -version
‘sclac‘ is not recognized as an internal or external command,
operable program or batch file.

C:\Users\guowli>scala
Welcome to Scala 2.12.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions for evaluation. Or try :help.

scala> println("Hello Scala!")
Hello Scala!

scala> :quit

C:\Users\guowli>

2.5-scala命令幫助信息

C:\Users\guowli>scala -help
Usage: scala <options> [<script|class|object|jar> <arguments>]
   or  scala -help

All options to scalac (see scalac -help) are also allowed.

The first argument to scala after the options designates what to run.

If no argument is given, the Scala REPL, an interactive shell, is started.

Otherwise, the Scala runner will try to run the named target, either as
a compiled class with a main method, a jar file with a Main-Class manifest
header, or as a Scala source file to compile and run.

The REPL accepts expressions to evaluate. Try `:help` to see more commands.

The script runner will invoke the main method of a top-level object if
it finds one; otherwise, the script code is run locally to a synthetic
main method with arguments available in a variable `args`.

Options to scala which reach the Java runtime:

 -Dname=prop  passed directly to Java to set system properties
 -J<arg>      -J is stripped and <arg> passed to Java as-is
 -nobootcp    do not put the Scala jars on the boot classpath (slower)

Other startup options:

 -i <file>    preload <file> before starting the REPL
 -I <file>    preload <file>, enforcing line-by-line interpretation
 -e <string>  execute <string> as if entered in the REPL
 -save        save the compiled script in a jar for future use
 -nc          no compilation daemon: do not use the fsc offline compiler

If the runner does not correctly guess how to run the target:

 -howtorun    what to run <script|object|jar|guess> (default: guess)

When running a script or using -e, an already running compilation daemon
(fsc) is used, or a new one started on demand.  Use the -nc option to
create a fresh compiler instead.


C:\Users\guowli>

3- 運行第一個scala程序

3.1- 官網示例

http://www.scala-lang.org/documentation/your-first-lines-of-scala.html

3.2- 利用Scala-IDE

  1. Create Scala Project : File--》New--》Scala Project--》Enter a project name.--》Next--》Check or Define the Scala build settings.---》Finsh
  2. Create Package : Choose src folder--》right-click,New--》Package--》Enter a package name.--》Finsh.
  3. Create Scala Object : Choose package--》right-click,New--》Scala Object--》Enter a object name.--》Finsh.
  4. Run code : Choose Scala file--》right-click,Run As--》Scala Application.
package test

object helloscala {
  def main(args: Array[String]) {
    println("Hello, Scala!")
  }
}

技術分享圖片

3.3- 命令行下的編譯與執行

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven/Anliven-Code/ScalaProjects
$ mkdir Testing

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven/Anliven-Code/ScalaProjects
$ cd Testing/

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven/Anliven-Code/ScalaProjects/Testing
$ ls -l
total 0

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven/Anliven-Code/ScalaProjects/Testing
$ vim Testing.scala

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven/Anliven-Code/ScalaProjects/Testing
$ cat Testing.scala
object Testing extends App {
  println("Hello, "+args(0)+"!")
}

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven/Anliven-Code/ScalaProjects/Testing
$ scalac Testing.scala

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven/Anliven-Code/ScalaProjects/Testing
$ ls -l
total 13
-rw-r--r-- 1 anliven 197121 2752 10月 25 23:58 ‘Testing$.class‘
-rw-r--r-- 1 anliven 197121  767 10月 25 23:58 ‘Testing$delayedInit$body.class‘
-rw-r--r-- 1 anliven 197121  768 10月 25 23:58  Testing.class
-rw-r--r-- 1 anliven 197121   64 10月 25 23:58  Testing.scala

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven/Anliven-Code/ScalaProjects/Testing
$ scala Testing Anliven
Hello, Anliven!

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven/Anliven-Code/ScalaProjects/Testing
$ ls -l
total 13
-rw-r--r-- 1 anliven 197121 2752 10月 25 23:58 ‘Testing$.class‘
-rw-r--r-- 1 anliven 197121  767 10月 25 23:58 ‘Testing$delayedInit$body.class‘
-rw-r--r-- 1 anliven 197121  768 10月 25 23:58  Testing.class
-rw-r--r-- 1 anliven 197121   64 10月 25 23:58  Testing.scala

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven/Anliven-Code/ScalaProjects/Testing
$

4- REPL(Read Evaluate Print Loop)

REPL(Read-Eval-Print Loop,交互式解釋器)是輕量級的交互式的程序運行環境,適用於小段程序的實驗和驗證。

4.1-命令行方式

$ scala
Welcome to Scala 2.12.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_131).
Type in expressions for evaluation. Or try :help.

scala> println("Hello, Scala!")
Hello, Scala!

scala> val x=1
x: Int = 1

scala> println(x)
1

scala> :quit

4.2-sbt方式

獲取SBT的幫助信息在命令行下執行“sbt -h”,或者執行“sbt”後輸入help並回車。

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven
$ sbt console
[warn] No sbt.version set in project/build.properties, base directory: D:\Anliven
[info] Set current project to anliven (in build file:/D:/Anliven/)
[info] Starting scala interpreter...
Welcome to Scala 2.12.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_131).
Type in expressions for evaluation. Or try :help.

scala> println("Hello, Scala!")
Hello, Scala!

scala> val x=2
x: Int = 2

scala> println(x)
2

scala> :quit

[success] Total time: 41 s, completed 2017-10-25 23:52:39

anliven@DESKTOP-68OFQFP MINGW64 /d/Anliven
$

4.3-IDE方式

  1. Create Scala Project : File--》New--》Scala Project--》Enter a project name.--》Finsh
  2. Create Package : Choose project 》right-click,New--》Scala Worksheet--》Enter a Worksheet name.--》Finsh.
  3. Create code in .sc file: Save .sc file and check the output in the .sc file.
  println("Welcome to the Scala worksheet")       //> Welcome to the Scala worksheet
  var x = 1                                       //> x  : Int = 1
  println(x)                                      //> 1

技術分享圖片

5- 在Ubuntu系統安裝Scala

5.1-安裝JDK

root@Ubuntu16:~# apt-get update
root@Ubuntu16:~#
root@Ubuntu16:~# apt-get install openjdk-8-jre openjdk-8-jdk
root@Ubuntu16:~#
root@Ubuntu16:~# java -version
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-0ubuntu0.16.04.2-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)
root@Ubuntu16:~#

5.2-配置環境變量JAVA_HOME

root@Ubuntu16:~# dpkg -L openjdk-8-jdk | grep ‘/bin‘|head -1
/usr/lib/jvm/java-8-openjdk-amd64/bin
root@Ubuntu16:~# vim ~/.bashrc 
root@Ubuntu16:~# source ~/.bashrc
root@Ubuntu16:~# cat ~/.bashrc|head -1
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
root@Ubuntu16:~# 
root@Ubuntu16:~# echo $JAVA_HOME
/usr/lib/jvm/java-8-openjdk-amd64
root@Ubuntu16:~# 
root@Ubuntu16:~# $JAVA_HOME/bin/java -version
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-0ubuntu0.16.04.2-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)
root@Ubuntu16:~# 
root@Ubuntu16:~# javac -version
javac 1.8.0_151
root@Ubuntu16:~# $JAVA_HOME/bin/javac -version
javac 1.8.0_151
root@Ubuntu16:~#

5.3-安裝Scala

wget https://downloads.lightbend.com/scala/2.12.4/scala-2.12.4.tgz
root@Ubuntu16:~# ls -l scala-2.12.4.tgz 
-rw-r--r-- 1 root root 19741785 10月 11 16:05 scala-2.12.4.tgz
root@Ubuntu16:~# 
root@Ubuntu16:~# tar -zxf scala-2.12.4.tgz -C /usr/local
root@Ubuntu16:~# cd /usr/local
root@Ubuntu16:/usr/local#
root@Ubuntu16:/usr/local# mv ./scala-2.12.4/ ./scala
root@Ubuntu16:/usr/local#
root@Ubuntu16:/usr/local# chown -R root ./scala
root@Ubuntu16:/usr/local#
命令說明:“ tar -zxf scala-2.12.4.tgz -C /usr/local”
  • x : 從 tar 包中把文件提取出來;
  • z : 表示 tar 包是被 gzip 壓縮過的,所以解壓時需要用gunzip解壓;
  • f : 表示後面跟著的是文件;
  • C:表示文件解壓後轉到指定的目錄下

5.4-配置環境變量PATH並運行scala

root@Ubuntu16:/usr/local# vim ~/.bashrc 
root@Ubuntu16:/usr/local# source ~/.bashrc
root@Ubuntu16:/usr/local# cat ~/.bashrc |head -1
export PATH=$PATH:/usr/local/scala/bin
root@Ubuntu16:/usr/local# 
root@Ubuntu16:/usr/local# scala
Welcome to Scala 2.12.4 (OpenJDK 64-Bit Server VM, Java 1.8.0_151).
Type in expressions for evaluation. Or try :help.

scala> :help
All commands can be abbreviated, e.g., :he instead of :help.
:edit <id>|<line>        edit history
:help [command]          print this summary or command-specific help
:history [num]          show the history (optional num is commands to show)
:h? <string>            search the history
:imports [name name ...] show import history, identifying sources of names
:implicits [-v]          show the implicits in scope
:javap <path|class>      disassemble a file or class name
:line <id>|<line>        place line(s) at the end of history
:load <path>            interpret lines in a file
:paste [-raw] [path]    enter paste mode or paste a file
:power                  enable power user mode
:quit                    exit the interpreter
:replay [options]        reset the repl and replay all previous commands
:require <path>          add a jar to the classpath
:reset [options]        reset the repl to its initial state, forgetting all session entries
:save <path>            save replayable session to a file
:sh <command line>      run a shell command (result is implicitly => List[String])
:settings <options>      update compiler options, if possible; see reset
:silent                  disable/enable automatic printing of results
:type [-v] <expr>        display the type of an expression without evaluating it
:kind [-v] <type>        display the kind of a type. see also :help kind
:warnings                show the suppressed warnings from the most recent line which had any

scala> :quit
root@Ubuntu16:/usr/local#

5.5-運行示例

root@Ubuntu16:~/testcode# ls -l
總用量 4
-rw-r--r-- 1 root root 96 11月 14 17:10 test.scala
root@Ubuntu16:~/testcode# 
root@Ubuntu16:~/testcode# cat test.scala 
object HelloWorld {
    def main(args: Array[String]){
        println("Hello, World!")
    }
}
root@Ubuntu16:~/testcode# 
root@Ubuntu16:~/testcode# scalac test.scala 
root@Ubuntu16:~/testcode# ls -l
總用量 12
-rw-r--r-- 1 root root 602 11月 14 17:11 HelloWorld.class
-rw-r--r-- 1 root root 665 11月 14 17:11 HelloWorld$.class
-rw-r--r-- 1 root root  96 11月 14 17:10 test.scala
root@Ubuntu16:~/testcode# 
root@Ubuntu16:~/testcode# scala -classpath . HelloWorld
Hello, World!
root@Ubuntu16:~/testcode# ls -l
總用量 12
-rw-r--r-- 1 root root 602 11月 14 17:11 HelloWorld.class
-rw-r--r-- 1 root root 665 11月 14 17:11 HelloWorld$.class
-rw-r--r-- 1 root root  96 11月 14 17:10 test.scala
root@Ubuntu16:~/testcode# 
註意:
  • 關於main()方法的定義,Scala中則必須使用對象方法,而在Java中是用靜態方法(public static void main(String[] args))。
  • 對象的命名HelloWorld可以不用和文件名稱一致,這點和Java不同。
scalac test.scala  # 編譯的時候使用的是Scala文件名稱
scala -classpath . HelloWorld  # 執行的時候使用的是HelloWorld對象名稱

 

 

Scala - 02 - 搭建開發環境