What Java developers can gain from Scala
See how Scala goes further, bringing powerful features such as type safety, implicit parameters, and compile-time insights that change the way you develop on the JVM.
The JVM appeared in 1994 to run Java programs, but it stopped being a Java-only platform long ago. Plenty of other languages make use of its capabilities, Scala among them. If you’re a Java developer who has heard or read a little about Scala, you may assume that all it brings is some syntactic sugar. In this article, I’ll try to persuade you that it offers a lot more.
There is some syntactic sugar as well, among other things, but that’s not what this article is about. I’ll concentrate on 3 features that Java lacks and which, IMHO, are the most powerful and make the biggest difference. These are type safety, implicit parametersandclasses, and information available at compile time.
Type Safety
Is Java type safe? Certainly. But what does that actually mean? Is type safety a “yes or no” matter, or is it more of a spectrum? Put differently, can two languages both be type safe while one is “type safer” than the other? IMHO, yes, it can, and Scala is “type safer” than Java. The reason lies in the “covariance” and “contravariance” mechanisms implemented for generic types. They provide a way of establishing inheritance relationships between types based on their generic type. An example explains it best:
In Java, a List of Integers is not a List of Objects, even though every Integer is an Object. The following code doesn’t compile:
List<Integer> listOfInts = new List();
List<Object> listOfObjects = listOfInts // compile time error
In Scala, on the other hand, this code compiles:
val listOfInts: List[Int] = List()
val listOfObjects: List[Object] = listOfInts
How come? It works because Scala’s List is covariant in its element (generic) type. Have a look at how List is declared in Scala:
sealed abstract class List[+A] extends AbstractSeq[A]
See the + sign beside the generic type? It indicates that List is covariant in its generic type, meaning that a List whose elements are of a subtype of A is itself a subtype of a List whose elements are of type A. That may still sound vague, but stick with me. Examples come to the rescue:
A List of apples is a subtype of a List of fruits:
val listOfApples: List[Apple] = List(grannySmith, goldenDelicious, gala)
val listOfFruits: List[Fruit] = listOfApples
A List of dogs is a subtype of a List of animals:
val listOfDogs: List[Dog] = List(
frenchBulldog,
goldenRetriever,
germanShepherd
)
val listOfAnimals: List[Animal] = listOfDogs
A List of any type A is a subtype of a List of a supertype of A. Every one of these assignments works and the compiler raises no objections. Naturally, you can’t assign a supertype to a subtype: val listOfDogs = listOfAnimals won’t compile.
Thanks to this simple mechanism, there’s no need to convert a list of subtypes before assigning it to a val typed as a list of supertypes.

Contravariance is the “reverse” rule. It’s declared with a minus sign (-), and ParamType[-T] says that ParamType is contravariant in its generic type T. In other words, a ParamType[A] is a subtype of a ParamType[B] when B is a supertype of A. This may appear nonsensical, but it has good use cases too.
A type accepted by a function (the type of a function parameter) is an example of a contravariant type. A function that takes one parameter and returns a value is contravariant in its parameter type and covariant in its return type. Yes, a type (Function1 here) can be covariant in one type parameter and contravariant in another. A single-parameter function implements the Scala trait Function1(shown here in simplified form):
trait Function1[-T1, +R]
It’s plainly contravariant in one type and covariant in the other. The contravariant one (-T1) is the type of the parameter the function takes, while the covariant one (+R) is the type the function returns. Why is one covariant and the other contravariant? It all adds up.
Take the class Apple extending Fruit, and Horse extending Animal. Now take a function with the signature Animal => Apple (it accepts 1 parameter of type Animal and returns Apple), for example whatItLikes(animal: Animal): Apple, which returns an animal’s favourite kind of apple.
Next, picture a service HorseService, whose constructor requires a function of type Horse => Fruit. Thanks to type variance, we can still pass in the whatItLikes function! It is contravariant in the parameter type – Animal is a supertype of Horse – and covariant in the return type – Apple is a subtype of Fruit – so it fits! Put another way, the function type Function1[Animal, Apple] is a subtype of Function1[Horse, Fruit]., because Animal is a supertype of Horse and Apple is a subtype of Fruit. This becomes clear when you consider where it can be used. As in the example above, when a function accepting Horse and returning Fruit is required, we can still supply a function that accepts any Animal (since it accepts any Horse too) and returns Apple (since an Apple is always acceptable where a Fruit is expected).
It makes sense because, in general, a parameter can be passed to a function that accepts its supertype, and a value returned by a function is accepted if it is a subtype of the expected type.

As Scala developers, we rarely have to deal with type variance in our daily work, but the libraries we rely on use it, which makes them more useful and safer (in the type safety sense) and spares us some runtime errors.
Implicits
An implicit is a value, parameter, or function that the compiler applies automatically (implicitly) wherever it’s needed, without it having to appear explicitly in the code. For instance, to call a method declared as follows:
def encode[A](a: A)(using enc: Encoder[A])
writing encode(a) is enough, provided an implicit encoder for the type of a exists and is in scope. The compiler will fill in the enc parameter for us.
At first sight, implicits look like syntactic sugar – programmers can skip certain parameters because the compiler supplies them automatically. Yet thanks to implicit functions (automatic conversion from one parameter to another), they are far more powerful than they appear.
Scala 3 has several kinds of implicits – implicit parameters, conversions, extensions, and so on. We’ll take a quick look at each, and then try to build something useful by combining various implicits in Scala 3.
Implicit parameter
This lets you avoid writing the variable name every time it’s needed. It comes in handy for parameters handed down from a higher-level function to a lower one, then to another lower one, and so on. Things like context, default values, timeouts, etc. usually originate at the top but are needed several levels further down. Rather than threading it through manually, you can make it implicit so it’s passed along automatically:
@main
def main(): Unit = {
given timeout: Timeout = Timeout(3)
val value = doSomething
println(value)
}
def doSomething(using Timeout) = {
doSomethingDeeper
}
def doSomethingDeeper(using timeout: Timeout): String = {
s"done in less than ${timeout.seconds} seconds"
}
You don’t need to pass timeout to doSomething or to doSomethingDeeper – it’s handed over automatically. If an implicit parameter isn’t used explicitly within a scope, it doesn’t need a name – look at how doSomething is declared: it has using Timeout with no parameter name, just to indicate that the implicit parameter is required without naming it. In a sense this resembles Java’s ScopedValue, except that it must be declared in every method along the call path – in the example above, doSomething also declares the implicit Timeout parameter even though it doesn’t use it. On the other hand, implicits aren’t restricted to parameters – implicit classes and methods exist as well, so keep reading.
Implicit conversion
Occasionally a value has to be converted to a different type. Suppose you need to turn Meters into Yards. With an implicit conversion in scope, this can happen automatically: Meters can then be used wherever Yards are expected, and they’ll be converted on the fly!
case class Meters(value: Double)
case class Yards(value: Double)
given Conversion[Meters, Yards] = m => Yards(m.value * 1.094)
@main
def main2(): Unit = {
val distance = Meters(10)
go(distance)
}
def go(distance: Yards): Unit = {
println(s"Going ${distance.value} yards")
}
Although go takes Yards rather than Meters, it still works thanks to the implicit conversion. The Meters passed as an argument get converted into Yards.
Extension methods
Extension methods are the third kind of implicits in Scala 3. You can think of them as “conversion to a type that has the method implemented”. Say Doubles are used somewhere, but we’d like to be more precise and type safe, ensuring that a given double value represents a distance in Meters. We can add an extension method .asMeters to the Double type!
extension(distanceInMeters: Double) def asMeters(): Meters =
Meters(distanceInMeters)
@main
def main3(): Unit = {
val distance = 10
go(distance.asMeters())
}
This makes it possible to extend the behavior of (add methods to) a type the programmer doesn’t control – one coming from a library, for example. There are other ways of achieving this, such as wrapping the type in a ValueObject, but I’d argue extension methods are the better choice. Their advantage is that a type can have many extension methods (possibly from different libraries), whereas having many ValueObjects for one type is awkward. A type wrapped in one VO can’t simultaneously be wrapped in another VO.Unwrapping it and re-wrapping it in a different VO is required and inconvenient.
Information available at compile time
Java exposes plenty of information about classes, their fields, methods and so on at runtime. That enables generic encoders, serializers, etc., but if something is wrong – say a field is expected but the class doesn’t have it – it will fail at runtime. Scala 3 makes far more information available at compile time, so if certain assumptions aren’t satisfied, the code simply won’t compile.
Mirror
Information about a case class (a case class is similar to a record in Java) and the types of its fields is supplied by Mirror.Of[A] – a type built at compile time that holds this information in the form of other types. Everything here lives at the type level rather than the value level, and is available at compile time. It lets you obtain a case class’s type name, its field types, labels and so on.
constValue
constValue is a method in the scala.compiletime package that returns the value of a constant type. What’s a constant type? It’s a type that has just one possible value. In fact, when you create a value in Scala 3 like
val a = 1
the type of a is Int, but it’s also 1. Yes, 1 here is a type – it obviously extends Int, and normally we don’t need it and just use Int, but it’s a distinct type nonetheless. It’s a constant type with a single possible value: 1. So constValue is a method returning the value – in other words the (one and only) instance – of such a type.
constValue works only in an inlined context, because the type passed in must be known at compile time. We’ll come back to inline later.
erasedValue
erasedValue also lives in scala.compiletime, and it produces a “virtual instance” of a type at compile time. It’s useful when you need information about a type whose value doesn’t even exist at runtime – erasedValue creates such a virtual value. We’ll use it to pattern match on the types of case class members taken from Mirror.Of.
inline
An inline method is one whose call the compiler replaces with the method’s body. In our example we’ll use an inline match, which gets reduced at compile time to just one pattern-match branch. For example
inline b match {
case true => "matches!"
case false => "no match, sorry"
}
will be replaced at compile time with plain "matches!" or "no match, sorry". Naturally, for this to work the value of b must also be known at compile time; otherwise, the compiler will raise an error.
Let’s build something useful
At first sight, implicits may look like mere syntactic sugar that only saves us some typing. Used sensibly, though, they can be a powerful tool. They can also do damage when misused – consider yourself warned ;) One (good) use of implicits is generating encoders/decoders and serializers/deserializers. JSON encoders/decoders are the most common, but any other format such as CSV, Protobuf etc. works too. JSON is a good fit because it’s schema-less and supports nested objects, which gives a chance to show how implicits help generate nested encoders. In this example we’ll build something simpler, yet schemaless and with nesting just like JSON. The encoder is generic and works for any case class (a case class is similar to a record in Java, remember?) containing other nested case classes. Well, perhaps not any – traits, collections etc. aren’t supported – but it’s enough to demonstrate what implicits are capable of. Take two simple case classes
case class User(name: String, age: Int, address: Address)
and
case class Address(
country: String,
city: String,
street: String,
number: Int
)
We won’t use any runtime reflection. If something is off and an instance can’t be encoded, we want to learn about it at compile time.
Another goal is ease of use, roughly like this:
val user = User(
"Paul",
45,
Address("Germany", "Hamburg", "Lindenstrasse", 10)
)
val encoded = Encoder.encode(user)
Clearly, we need an Encoder object with an encode method
object Encoder {
def encode[A](value: A)(using enc: Encoder[A]): String = ...
In Scala, an object is a singleton. It’s where you put methods that would be static in java – those that don’t require class instances. The declaration of the encode method says it takes one “regular” parameter value of type A, plus one implicit parameter of type Encoder[A].
Within this method, A is a generic type. It can be any type, and the declaration needs it for the enc parameter. enc is an Encoder parametrized with the generic type, which has to be the same type that value is an instance of. That’s the only constraint on the generic type A here and the only reason we need it – to express that the Encoder’s generic type must match the type of value.
enc sits in its own parameter list – yes, in Scala a method can have more than one parameter list. The using keyword marks the parameters in this list as implicit – meaning we don’t have to write them out if an implicit parameter of that type is in scope.
Now let’s write the method body. Once the required encoder is available, it looks simple:
def encode[A](a: A)(using enc: Encoder[A]): String = enc.encode(a)
This way, implicit encoders of the appropriate type get used – which proves useful when encoding nested types.
So an implicit Encoder for type A has to be in scope – but where does it come from? It’s supplied by an implicit method
inline implicit def makeEncoder[A](using m: Mirror.Of[A]): Encoder[A]
For the body of this method, we need some of the tools described earlier. This encoder’s job is to output the class name along with the names and values of all its members – much like JSON, only simpler: we leave out braces and don’t care about formatting. All of this information is obtained at compile time. Let’s see the methods that do it:
inline implicit def makeEncoder[A](using m: Mirror.Of[A]): Encoder[A] =
(a: A) => {
val labels: Seq[String] = deconstructLabels[m.MirroredElemLabels]
val memberEncoders: Seq[Encoder[Any]] =
deconstructMemberEncoders[m.MirroredElemTypes]
val lines = a.asInstanceOf[Product].productIterator
.zip(labels)
.zip(memberEncoders)
.map {
case ((value, label), memberEncoder) =>
s"$label: ${memberEncoder.encode(value)}"
}
constValue[m.MirroredLabel] + "\n" + lines.mkString("\n")
}
The makeEncoder method relies on a few helper methods to obtain the case class fields, their names and types, and the case class name, and in the end it builds a nicely formatted String containing all of that.
labels holds the member labels, so for Address, for instance, they’ll be “country”, “city”, “street” and “number”.
memberEncoders holds encoders for every member of the case class, in order.
One notable bit here is a.asInstanceOf[Product]. Every case class in Scala is also an instance of Product. The Product trait provides productIterator – an iterator over all the case class fields. After zipping it with labels (the field names) and memberEncoders, we can handle the fields one at a time, each with its value, label and memberEncoder.
The final line of the makeEncoder method just prepends m.MirroredLabel, which holds the case class name.
Now for the last missing pieces – the deconstructLabels and deconstructMemberEncoders methods.
inline def deconstructLabels[T <: Tuple]: List[String] =
inline erasedValue[T] match
case _: (head *: tail) =>
constValue[head].asInstanceOf[String] :: deconstructLabels[tail]
case _: EmptyTuple => List.empty
The method above creates a “virtual” value (one that doesn’t really exist at runtime) of type T, which here is MirroredElemLabels from Mirror.Of. It then pattern matches on its type. The type is a Tuple, and you can match on it much as you would on a list – head and tail (tail may be an empty list) or EmptyTuple. Recursively, when it’s head and tail (keep in mind both are types, not values – remember constant types?), it reads head as an instance of String (these are labels, so they’re always Strings) and deconstructs tail. That’s how a list of all the labels gets built.
Now look at the other method – deconstructMemberEncoders. It’s slightly more involved, but bear with me.
inline def deconstructMemberEncoders[T <: Tuple]: List[Encoder[Any]] =
inline erasedValue[T] match
case _: (head *: tail) =>
val encoder = summonInline[Encoder[head]]
encoder.asInstanceOf[Encoder[Any]] ::
deconstructMemberEncoders[tail]
case _: EmptyTuple => List.empty
As before, we need erasedValue to match on the type T. Again, the generic type T is always a tuple, but this time it’s a tuple of field types rather than labels. So they aren’t all Strings but types such as Int, String, Address etc. For each member type, an Encoder is summoned. Summoning means obtaining an implicit value if one is in scope. If there isn’t one, compilation fails – all implicits are resolved at compile time, not at runtime. Encoders for primitives (to keep it simple we only use String and Int) must be in scope as well, and we add them explicitly. Yes… implicits, explicitly… For those two, we need lines like these:
given Encoder[String] with
def encode(a: String): String = a
given Encoder[Int] with
def encode(a: Int): String = a.toString
This defines encoders for String and Int and, through the given keyword, places them in scope as implicits. The Encoder for Address is in implicit scope too, even though we never create it! The implicit method makeEncoder produces it automatically. That’s what I meant by “some implicits are added to scope explicitly”. A few of them we have to write by hand, while the one for Address will be generated by our magical method.
With all these pieces in place, we have a tool that encodes any case class whose members are String or Int, or other nested case classes that also contain fields of those types. And all of it at compile time! If it compiles, a call to Encoder.encode(x) is guaranteed to always return a nicely formatted string with all the information about x.
Summary
Scala brings some distinctive features absent from Java that reach well beyond simple syntactic convenience. Chief among them is an advanced type system that supports variance in generics and allows for more robust polymorphism. Implicits enable automatic parameter passing, type conversions and generation, which makes it possible to derive type classes for nested types. Scala’s compile-time capabilities, such as inline functions that expose information about types, help catch errors early and improve performance. Taken together, these features make Scala an attractive option for Java developers looking for a more expressive and dependable way of programming.