How to save and reuse Scala utility code

What is a good approach for collecting and using useful Scala utility features for all projects. The focus here is on really simple, stand-alone functions, such as:

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 the main one, I know ;-), but, I found out that there is always an optimal way to do something. For example, reusing code from the Scala, Idea, Eclipse interactive shell, with or without SBT, with a library running on GitHub, etc., can quickly introduce optimal and non-optimal approaches to such a simple problem.

+4
source share
2 answers

You might want to place such methods in an object.

You can also put them in a regular object and import everything into the object when you need these methods.

 object Utilities { def toBinary(i: Int, digits: Int = 8) = // ... } // Import everything in the Utilities object import Utilities._ 
+7
source

If you want it to be accessible trivially from anywhere in the world, it is best to stick it in a scala -library jar. Personally, I have all my settings in /jvm/S.jar (or something like that) and add it to the classpath every time I need it.

Repacking a Scala library is very simple - unzip it, move the class hierarchy, and repack it. (You must have it inside any package and / or package object.)

+1
source

Source: https://habr.com/ru/post/1398354/


All Articles