user1585455
user1585455

Reputation:

How to use packages in Scala?

I am currently learning Scala and found this awesome framework called Squants that does all sorts of cool things like conversions. The problem is: I have no idea how to use it.

I come from a background of ruby gems and node packages, so I expected Scala to have a similar aspect to it.

The documentation I found didn't help much so I started searching different terms. I found this Stack Overflow question which addressed the issue with something called "sbt". I already know how to compile files with scalac and run them with scala, so I was a bit confused by what sbt was until I did some research. I tried to follow the instructions and replace the libraryDependencies with "com.squants" %% "squants" % "0.4.2", but that just threw a ton of errors in the sbt console. Ultimately, I want the package working with my code, not in a console.

I then found the framework on a website called Sonatype. I downloaded a jar file from this website but am not sure how to use jar files in Scala (if possible?). Searching for this revealed some not-so-beginner-friendly results.

For reference, this is my scala file that I am using to test the package:

import com.squants._

object HelloSquants {
    def main(args: Array[String]): Unit = {
        val x: Power = Kilowatts(12)
        val y: Power = Megawatts(0.023)
        val sum = x + y
        println(x + " plus " + y + " equals " + sum)
    }
}

What is the proper way to get this package working in Scala?

Upvotes: 1

Views: 176

Answers (1)

bwawok
bwawok

Reputation: 15347

Hum lots of questions.

First off, you are confusing terms a little. A package is the name space of your code. You can write some code

package foo {
  class Apple...
}

package bar {
  class Apple...
}

Then depending on which Apple class you want to use, you can either import foo.Apple, or bar.Apple. Foo and bar are the packages.. you don't really mean packages.

Sbt is a necessary evil to learn. Scala projects get big, and you pull in a bunch of libraries. I think when you said package you meant library

So yes, follow some simple SBT tutorials... a good starting place is http://www.scala-sbt.org/release/tutorial/

Adding

"com.squants"  %% "squants"  % "0.4.2"

To your build.sbt is correct, and it will download the squants library, and include it in your compile path. However it does not automatically add it to your run path. For that, I suggest you code in idea https://www.jetbrains.com/idea/ , so that it will see your build.sbt file, and add the correct stuff to your classpath for you.. then you should be able to right click and run your code.

Upvotes: 1

Related Questions