home search about rss feed twitter ko-fi

Importing Code, Part 2 (Scala 3 Video)

Import Statements

  • Some built-in Scala types and functions are automatically available to you
    • List, Vector, Seq, Map, Set, String, Int, Double, Boolean, println (and more)
  • These work because these three packages are implicitly imported for you:
java.lang.*
scala.*
scala.Predef.*

Everything else is NOT automatically available:

  • mutable collections
  • every third-party library

In this video I show several ways to use Scala import statements.

To use a third-party library

  • Configure how to access/download it in your build tool (such as by adding the correct entry in build.sbt when using the SBT build tool)
    • (This code is said to be “packaged” so you can use it)
  • Then import it into your code with the correct import statement

Example usage

My “utilities” library looks like this:

package com.alvinalexander.utils

object StringUtils:

    // convert "big belly burger" to "Big Belly Burger"
    def capitalizeAllWords(s: String): String =
        s.split(" ")
         .map(_.capitalize)
         .mkString(" ")

    def isBlank(s: String): Boolean =
        s.trim == ""

    def isNullOrEmpty(s: String): Boolean = 
        if s == null || isBlank(s) then true else false
    
    // this code goes on for a while ...

I don’t demonstrate how to configure it in build.sbt, but I show several ways to import it in other code:

package foo

import com.alvinalexander.utils.StringUtils.capitalizeAllWords
import com.alvinalexander.utils.StringUtils.truncate
import com.alvinalexander.utils.StringUtils.truncateWithEllipsis

@main def stringUtilsTest(): Unit =

    val bbb = "big belly burger"

    val capWords = capitalizeAllWords(bbb)
    println(capWords)

    println(truncate(bbb, 9))
    println(truncateWithEllipsis(bbb, 9))

Update: All of my new videos are now on
LearnScala.dev