DJ180 DJ180 - 25 days ago 8
Scala Question

Scala Generics with case class extending sealed trait

The following code will not compile, and I don't understand the reasons why not

class FruitProcessor[T <: Fruit] {
def process(fruit: T) = {
// Do something with fruit

class FruitBlender[T <: Fruit] {
val fruitProcessor = new FruitProcessor[T]

def blend(fruit: T) = {
fruit match {
case b: Banana => fruitProcessor.process(b)
case a: Apple => fruitProcessor.process(a)

sealed trait Fruit
case class Banana(id: String) extends Fruit
case class Apple(id: String) extends Fruit

The compilation error is along the lines of "found Banana, required T"

What am I doing wrong here?


The process method requires an argument of type T, but you pass it a value of type Banana. The compiler isn't smart enough to figure out that T is always Banana in the code path where fruitProcessor.process(b) is called. Actually you don't need that match expression at all. In this case the T in the method blend is the same as the T that process wants. So you can just call fruitProcessor.process(fruit).