Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import package into Scala REPL?

How do I import a package into Scala's REPL? I am trying to import this package called funsets which has an object named "FunSets". I tried several variations of import funsets._ and import funsets._; etc but it is still not importing the functions and object in the package.

like image 332
Linkx_lair Avatar asked Jan 03 '23 01:01

Linkx_lair


2 Answers

One way is to compile the "scala classes" and put those in classpath.

Example,

1) Say you have a class funsets.FunSets.scala

package funsets                                                                                        

object FunSets {                                                                                       

  def fun = "very fun"                                                                                 

}      

2) Compile the class first using scalac. (If you use sbt then sbt compile would put compiled classes in target/ folder)

scalac FunSets.scala

You will see the funsets folder/package created,

$ ls -l
total 16
-rw-r--r--  1 updupd  NA\Domain Users   63 Dec 18 11:05 FunSets.scala
drwxr-xr-x  4 updupd  NA\Domain Users  136 Dec 18 11:06 funsets

3) Then start REPL with funsets package in classpath

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

scala> import funsets._
import funsets._

Note: if you use sbt compile, put target/classes in classpath.

Access Funsets singleton,

scala> FunSets.fun
res0: String = very fun

Also read Scala REPL unable to import packge

like image 182
prayagupa Avatar answered Jan 05 '23 15:01

prayagupa


You need to add the appropriate jar(s) to the classpath as well using the -cp <jar files> argument when starting the repl. Alternatively you can use the :require <jar file> directive from the repl to load a jar after you've already started the session.

like image 20
puhlen Avatar answered Jan 05 '23 16:01

puhlen