Skip to main content

2 posts tagged with "Scala 2 => 3"

View All Tags

· 3 min read
Scala 2 => 3 Series

This is a part in an ongoing series dealing with migrating old ways of doing things from Scala 2 to Scala 3. It will cover the What's New in Scala 3 from the official site.

Check the Scala 2 => 3 tag for others in the series! For the repo containing all the code, visit GitHub. There are code samples for both Scala 2 and Scala 3 together, that are easy to run via scala-cli.

This post is centered around retroactively extending classes.

In Scala 2, extension methods had to be encoded using implicit conversions or implicit classes. In contrast, in Scala 3 extension methods are now directly built into the language, leading to better error messages and improved type inference.

Extensions are one of my favorite things to use in Scala. Personally, I like the ability to add functionality to "upstream" resources implicitly, but call that functionality explicitly. To me, it makes it less likely to break things during a refactor when you don't have to un-ravel a mysterious series of implicit def methods / conversions that you might not realize are being called.

The preface

For this example, let's say that we have some upstream domain model from a service we use but don't control.

case class UpstreamUser(id: Long, created: Instant, lastSeen: Instant)

In our service, we have a concept of when a user goes "stale" based on usage - but other services also have this notion, and differing beliefs about what conditions make a user stale - so we can't ask the upstream service to implement this for us on our model. Perhaps our model of what a stale user is changes over time as well.

Our conditions for a user going stale are:

  • A user was created over a year ago
  • A user hasn't been seen in the last week.

With that in mind, we could write some logic such as

import java.time.Instant
import java.time.temporal.ChronoUnit._
def isStale(created: Instant, lastSeen: Instant):Boolean = {
lastSeen.plus(7, DAYS).isBefore(Instant.now) &&
created.plus(365, DAYS).isBefore(Instant.now)
}

but calling that everywhere becomes a bit cumbersome, and it would be great if we could attach that functionality directly on UpstreamUser.

Scala 2

In scala 2, we can use an implicit class to achieve our goal. An implicit class should have only one constructor argument, of the Type that is being extended. It also needs to be housed in something, typically an outer object. This can make setting up implicit classes feel a bit "boilerplate-y".

object UpstreamUserExtensions {
implicit class ExtendedUpstreamUser(u: UpstreamUser) {
def isStale: Boolean = {
u.lastSeen.plus(7, DAYS).isBefore(Instant.now) &&
u.created.plus(365, DAYS).isBefore(Instant.now)
}
}
}

Now, with ExtendedUpstreamUser in scope to implicitly add our new functionality, we can (explicitly) call upstreamUserInstance.isStale as if it were on the model directly.

Scala 3

In Scala 3, it works much the same, but with less boilerplate. Instead of declaring an implicit class, you declare an extension: extension (u: UpstreamUser) where the argument matches the Type you're adding functionality to. This doesn't need to be housed in an object either!

The corresponding Scala 3 code would look like:

extension (u: UpstreamUser) {
def isStale: Boolean = {
u.lastSeen.plus(7, DAYS).isBefore(Instant.now) &&
u.created.plus(365, DAYS).isBefore(Instant.now)
}
}

and then we'll get the same upstreamUserInstance.isStale functionality as before.

Final Thoughts

Although the looks of the code have changed, if you're used to Scala 2 implicit classes, Scala 3 extensions will probably be a welcomed ergonomics change, with a familiar feel for usage.

· 4 min read
Scala 2 => 3 Series

This is a part in an ongoing series dealing with migrating old ways of doing things from Scala 2 to Scala 3. It will cover the What's New in Scala 3 from the official site.

Check the Scala 2 => 3 tag for others in the series! For the repo containing all the code, visit GitHub. There are code samples for both Scala 2 and Scala 3 together, that are easy to run via scala-cli.

This post is centered around the new way of passing implicit arguments to methods via using-clauses.

Abstracting over contextual information. Using clauses allow programmers to abstract over information that is available in the calling context and should be passed implicitly. As an improvement over Scala 2 implicits, using clauses can be specified by type, freeing function signatures from term variable names that are never explicitly referred to.

The preface

For this example, let's say that we have some interface that we're going to be passing around a lot, and that it could have multiple implementations.

trait BaseLogger {
def log[T](t: T): Unit
}

case class PrintLogger() extends BaseLogger {
def log[T](t: T): Unit = println(s"Logger result: ${t.toString}")
}

case class FancyLogger() extends BaseLogger {
def log[T](t: T): Unit = println(s"Ye Olde Logger result: ${t.toString}")
}

Scala 2

In Scala 2, we could write a method, and have our trait's implementation passed in as a separate implicit argument.

  def loggingOp[A,B](a: A, b: B)(implicit logger: BaseLogger): Int = {
val result = a.toString.map(_.toInt).sum + b.toString.map(_.toInt).sum
logger.log(result)
result
}

At this point, we could call our method by still passing the argument in explicitly

object Using_2 extends App {

val printLogger: PrintLogger = PrintLogger()
val fancyLogger: FancyLogger = FancyLogger()

loggingOp(40, 2)(printLogger)
loggingOp(40, 2)(fancyLogger)

}

However, if we define an instance of type BaseLogger in scope implicitly, then we don't need to pass it in as an argument every time! Of course, we still have the option to pass something in explicitly, if we don't want to use the instance that is in scope implicitly.


object Using_2 extends App {

val printLogger: PrintLogger = PrintLogger()
val fancyLogger: FancyLogger = FancyLogger()

loggingOp(40, 2)(printLogger)
loggingOp(40, 2)(fancyLogger)

// With an implicit of type BaseLogger in scope...
implicit val defaultLogger = printLogger

// ... I no longer need to pass it as an argument
loggingOp(true, false)
loggingOp(17, "purple")
// ... but I can still call implicit arguments explicitly!
loggingOp("car", printLogger)(fancyLogger)

}

Scala 3

In Scala 3, we don't use the implicit key word when defining a method - we now use using. A faithful port of the Scala 2 code above would look something like:

  // You can specify the name logger, but don't have to
def loggingOp_withParamName[A, B](a: A, b: B)(using logger: BaseLogger): Int = {
val result = a.toString.map(_.toInt).sum + b.toString.map(_.toInt).sum
logger.log(result)
result
}

The awesomeness of Scala 3 doesn't stop there, though, because you can define your methods by just declaring the type! In this case, we just summon an instance internally, and use reference to that.

There are only two hard things in Computer Science: cache invalidation and naming things.

Guess it's just invalidating caches now!

  def loggingOp[A, B](a: A, b: B)(using BaseLogger): Int = {
val logger = summon[BaseLogger]
val result = a.toString.map(_.toInt).sum + b.toString.map(_.toInt).sum
logger.log(result)
result
}

From here, our code works mostly the same - one caveat being that when explicitly passing arguments, you need to use the using keyword - where previously you didn't need to declare the values you were passing in were implicit. We're also declaring our BaseLogger in scope using alias givens

object Using_3 {

val printLogger: PrintLogger = PrintLogger()
val fancyLogger: FancyLogger = FancyLogger()

@main
def main = {

// We can still call things explicitly...
loggingOp(40, 2)(using printLogger)
loggingOp(40, 2)(using fancyLogger)

// .. but we have a new way of defining what type is in scope implicitly
// implicit val defaultLogger = printLogger // <- this would still work
given defaultLogger: BaseLogger = printLogger // <- but probably use this

loggingOp(true, false)
loggingOp(true, false)
loggingOp(17, "purple")
loggingOp("car", printLogger)(using fancyLogger)
}

}

Final Thoughts

Using clauses can be a bit more complex, but with the simple example outlined above - we have one less scary new thing, that we can mentally map back to our years of Scala 2 use!