Posts in the “scala” category

Scala inheritance tests: private, protected, def, val, and var

As a brief note, here are some tests I just created with Scala 3 to test concepts like private, protected, def, val, and var with inheritance tests, i.e., where classes extend other classes or traits:

// FAILS
// package private_def:
    // trait StoreProduct:
    //     private def id: Int   // compiler:
    //                           // "abstract method id may not have `private` modifier"
    //
    // class Pizza extends StoreProduct:
    //     val id = 1

package def_val:
    trait StoreProduct:
        protected def id: Int

    class Pizza extends StoreProduct:
        val id = 1

package val_val:
    trait StoreProduct:
        protected val id: Int

    class Pizza extends StoreProduct:
        val id = 1

package var_var:
    trait StoreProduct:
        protected var id: Int

    class Pizza extends StoreProduct:
        var id = 1

// FAILS
// package val_var:
//     trait StoreProduct:
//         protected val id: Int
//
//     class Pizza extends StoreProduct:
//         var id = 1      // compiler:
//                         // "variable id of type Int needs to be a stable, immutable value"

// FAILS
// package var_val:
//     trait StoreProduct:
//         protected var id: Int
//
//     class Pizza extends StoreProduct:
//         val id = 1      // compiler:
//                         // "class Pizza needs to be abstract, since protected
//                         // var id_=(x$1: Int): Unit in trait StoreProduct in
//                         // package var_val is not defined"

Hopefully you can see from the comments what works and what doesn’t work when you’re using inheritance in Scala.

Scala: Accessing a protected field when inheriting from a class in a different package

As a brief note, the Scala example at this URL (www.geeksforgeeks.org/controlling-method-scope-in-scala/) is not 100% correct, and this code Scala 3 code shows the issue and solution:

package a:
    class ClassA:
        protected var aProtected = 1
        var a = 1

package b:
    import a.ClassA

    class ClassB extends ClassA:
        a = 2
        aProtected = 2                   // ClassB *can* access this field.
        def getAProtected = aProtected   // make that field available to others
                                         //   via this public method.

    object Main:
        def main(args: Array[String]): Unit =
            val b = ClassB()
            b.a
            b.getAProtected   // compiles/works
            // b.aProtected   // does not compile

They correctly note that the variable I call aProtected can’t be accessed from the main method in the second package, but aProtected can be accessed by ClassB, which extends ClassA, though ClassB is in package b and ClassA is in package a.

So if you wanted to see an example of how to access a protected field in Scala code, where your class extends a class in a different package, and that original class has a protected field, I hope this example is helpful.

Java/Kotlin programmer holiday gift, 2022 (book)

As I mention in this blog post, in late November, 2022, my new book, Learn Functional Programming Without Fear, is a best-selling book in Amazon’s Java and functional programming categories.

The book is written for Java, Kotlin, and object-oriented programming (OOP) developers, and as a bonus, I made it less than half the price of other functional programming (FP) books. I hope this makes it a terrific 2022 holiday/Christmas gift for the Java, Kotlin, and OOP programmer in your life.

Great 2023 holiday programming gift book (for Java/Kotlin/OOP developers)

If you’re looking for a great Christmas/holiday gift for your favorite geek or programmer, I’ve reduced the price of my book, Learn Functional Programming The Fast Way! to just $20 for the holidays. It’s usually price at $29 or higher.

For a while there, the book was Amazon’s best-selling book in both their Java and functional programming categories, so although I’m biased, I think it’s a pretty good book.

The book is intentionally written for Java, Kotlin, and object-oriented programming (OOP) developers, and I also made the book much less expensive than other FP books to make Scala 3 and functional programming as accessible as possible to everyone. As a result, I hope it makes for a terrific 2023 Christmas/holiday gift for the Java/Kotlin/OOP computer programmer in your life!

Working with Parameterized Traits in Scala 3

This is a recipe from the Scala Cookbook (2nd Edition). This recipe is titled, Working with Parameterized Traits in Scala.

Problem

As you become more advanced in working with Scala types, you want to write a trait whose methods can be applied to generic types, or limited to other specific types.

Solution

Depending on your needs you can use type parameters or type members with traits. This example shows what a generic trait type parameter looks like:

Scala collections: Does filter mean retain/keep, remove

As an update before getting into the original article (below), I’ve come to think of the Scala filter method being spelled as the British filtre, and then I think of this acronym, which helps me remember how filter/filtre works: “Find In List Then Retain Each.” So basically filter means retain.

I know that’s a little hokey, but it works for me. And now, here’s the original article:

As part of my personal ongoing battle with the meaning of the filter method in functional programming languages like Scala, I decided to create add a keep method to the Scala List class using the Scala 3 extension method approach, like this:

Scala - How to declare an empty immutable Set (SortedSet)

I just saw this code that shows how to declare an empty immutable SortedSet in Scala, and wanted to save it as a helpful snippet here:

/**
 * The node ring gossipped that contains only members that are Up.
 */
var nodes: immutable.SortedSet[Address] = immutable.SortedSet.empty

Scala packaging and import examples

This article is a collection of Scala packaging and import examples. I created most of these examples when I was writing the 1st Edition of the Scala Cookbook. I share them here without much discussion, but for more examples and discussion, please check out the Cookbook.

Packages imported by default

By default, three packages are implicitly imported for you:

  • java.lang._
  • scala._
  • scala.Predef._

Passing an anonymous function to SwingUtilities.invokeLater (in Scala)

As a quick note, if you ever need to call the invokeLater of the Java SwingUtilities class in Scala, you can pass it an anonymous function (lambda) like this:

SwingUtilities.invokeLater(() => {
    // your gui-updating code here, such as:
    for (c <- newsControllers) c.updateContent()
})

(I haven’t worked with Java 8 lambdas too much, but I assume that the Java lambda syntax is similar to that.)