lets say we want to start a new scala project.
cd ~/Works
mkdir ScalaProject
So... the base directory
for our project is ~/Work/ScalaProject
.
Now, sbt will follow convention to try to find the following automatically,
- Sources in the
base directory
- Sources in
src/main/scala
orsrc/main/java
- Tests in
src/test/scala
orsrc/test/java
- Data files in
src/main/resources
orsrc/test/resources
- jars in
lib
build.sbt
located in base directory
Note :: The blank line after each statement in build.sbt
is important.
name := "ScalaProject"
version := "1.0"
scalaVersion := "2.11.8"
We can fix sbt
for our project in ScalaProject/project/build.properties
file.
sbt.version=0.13.12
Create src/main/scala/Demo.scala
object Demo {
def main(args: Array[String]) {
println("")
println("Hi,")
println("I am nothing but a Scala+Sbt Demo")
println("")
}
}
cd ~/Work/ScalaProject
# invoke sbt compiler; let it download things; will take some time
sbt compile
# after compiling run the code
sbt run
this will print something like this,
[info] Set current project to ScalaProject (in build file:/Users/xxxx/Works/ScalaProject/)
[info] Running Demo
Hi,
I am nothing but a Scala+Sbt Demo
[success] Total time: 1 s, completed 26 Aug, 2016 6:25:28 PM
Create a file src/main/scala/Utils.scala
Add few functions to our Utils
object Utils {
// A naive function for fibonacci numbers
def fibonacciSimple(n: Int): Int = {
n match {
case 0 => 1
case 1 => 1
case i => fibonacciSimple(n-1) + fibonacciSimple(n-2)
}
}
// tail recursion for better performence
def fibonacciTail(n: Int): Int = {
def _fibonacci(n: Int, m: Int, m1: Int, m2: Int): Int = {
if (n == m) m1 + m2
else _fibonacci(n, m + 1, m1 + m2, m1)
}
n match {
case 0 => 1
case 1 => 1
case i => _fibonacci(i, 2, 1, 1)
}
}
}
The above Scala code is equivalent to following JavaScript code,
var Utils = {
// A naive function for fibonacci numbers
fibonacciSimple = function(n) {
if (n == 0) return 1;
else if (n == 1) return 1;
else return fibonacciSimple(n-1) + fibonacciSimple(n-2);
},
// tail recursion for better performence
fibonacciTail: function(n) {
function _fibonacci(n, m, m1, m2) {
if (n == m) return m1 + m2
else return _fibonacci(n, m + 1, m1 + m2, m1)
}
if (n == 0) return 1;
else if (n == 1) return 1;
else return _fibonacci(i, 2, 1, 1);
}
}