home search about rss feed twitter ko-fi

Making Our Class More Generic (Scala 3 Video)

I wrote the previous lesson by creating a Wrapper[Int] so I wouldn’t have to deal with generic types in that lesson, but it’s simple to convert that class to a more generic class. All you have to do is:

  1. Change all the Int references to the generic A
  2. Change the map and flatMap signatures to return the generic type B

With those two changes you can convert this Int-specific code:

class Wrapper[Int](value: Int) {

    def map(f: Int => Int): Wrapper[Int] = {
        val newValue = f(value)
        new Wrapper(newValue)
    }

    def flatMap(f: Int => Wrapper[Int]): Wrapper[Int] = f(value)

    override def toString = value.toString
}

into this more generic code:

class Wrapper[A](value: A) {
    def map[B](f: A => B): Wrapper[B] = {
        val newValue = f(value)
        new Wrapper(newValue)
    }
    def flatMap[B](f: A => Wrapper[B]): Wrapper[B] = {
        val newValue = f(value)
        newValue
    }
    override def toString = value.toString
}

This generic class can still be used as a wrapper around Int in a for expression:

// (1) INT
val intResult: Wrapper[Int] = for {
    a <- new Wrapper(1)
    b <- new Wrapper(2)
    c <- new Wrapper(3)
} yield a + b + c

println(intResult)

And now it can also be used as a wrapper around String in a for expression:

// (2) STRING
val stringResult: Wrapper[String] = for {
    a <- new Wrapper("a")
    b <- new Wrapper("b")
    c <- new Wrapper("c")
} yield a + b + c

println(stringResult)

What’s next

There’s one more thing I’d like to do with this code: I’d like to change it so I don’t have to use the new keyword when creating each Wrapper instance. I’ll do that in the next lesson.

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