Why Scala 2.13 compiler doesn't allow nested generic type instantiation?

I have the following code that fails to compile.

package com.example

import scala.reflect.ClassTag

abstract class RDD[T: ClassTag]

class Dependency[T](_rdd: RDD[T]) {
  def rdd: RDD[T] = _rdd
}

class FakeRDD[T: ClassTag](deps: Dependency[_]) extends RDD[T]

object Hello {
  def main(args: Array[String]): Unit = {
    new FakeRDD(null)
    new FakeRDD(new Dependency(new FakeRDD(null))) // fails to compile
    println("Hello, Scala!")
  }
}

The error is from the line that has a trailing comment “fails to compile”. The error message is:

Hello.scala:16: No ClassTag available for T

However, if I use multiple lines, it can compile:

val d = new Dependency(new FakeRDD(null))
new FakeRDD(d)

Compiler tries to resolve types for all 3 parts of this expression at once:
new FakeRDD(new Dependency(new FakeRDD(null))) // fails to compile

It is not possible to create an external FakeRDD because new Dependency(…) does not provide information about target T type, because new Dependency(…) does not exist yet.
Scala tries to determine the types of all parts of this expression at once. This is too complex for the compiler.

In your second solution new Dependency(new FakeRDD(null)) already exist so previously external FakeRDD(d) can infer what the T is.

1 Like

What do you want the T to be in this case?

I want it be similar to null because I don’t care about the type. I just want the code to be concise and compile.