Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save and reuse Scala utility code

Tags:

scala

What is a nice approach for collecting and using useful Scala utility functions across projects. The focus here on really simple, standalone functions like:

def toBinary(i: Int, digits: Int = 8) =
    String.format("%" + digits + "s", i.toBinaryString).replace(' ', '0')

def concat(ss: String*) = ss filter (_.nonEmpty) mkString ", "
concat: (ss: String*)String

This question is basic, I know ;-) but, I've learned that there is always an optimum way to do something. For example, reusing code from within the Scala interactive shell, Idea, Eclipse, with or without SBT, having the library hosed on GitHub, ect, could quickly introduce optimal, and non-optimal approaches to such a simple problem.

like image 542
Jack Avatar asked Feb 25 '12 09:02

Jack


2 Answers

You might want to put such methods in a package object.

You could also put them in a normal object and import everything in the object when you need those methods.

object Utilities {
  def toBinary(i: Int, digits: Int = 8) = // ...
}

// Import everything in the Utilities object
import Utilities._
like image 142
Jesper Avatar answered Nov 12 '22 22:11

Jesper


If you want it trivially accessible from everywhere, your best bet is actually to stick it inside the scala-library jar. Personally, I have all my custom stuff in /jvm/S.jar (or something like that) and add it to the classpath every time I need it.

Repacking the Scala library jar is really easy--unpack it, move your class hierarchy in, and pack it up again. (You should have it inside some package and/or package object.)

like image 21
Rex Kerr Avatar answered Nov 13 '22 00:11

Rex Kerr