Search code examples
scalagenerics

Cannot resolve symbol T in Scala 2.12


The org.apache.parquet.column.statistics.Statistics class is defined in Java as public abstract class Statistics<T extends Comparable<T>>. I am writing a function in Scala that takes Statistics as an input parameter. The declaration I came up with is below which is giving me the error Cannot resolve symbol T. I understand the issue but can't quite figure out how to fix it.

def getMinMaxAsString(stats: Statistics[T <: Comparable[T]] ): (Option[String], Option[String]) = {
          (Some(""),Some(""))
}

Solution

  • When you want to introduce a type parameter T to a function, you have to first declare it between square brackets after the name of the function

    def functionName[A,B](param: A): B = ???
                     ^ ^
    

    A and B are two type paremeters. Also you can add upper type bounds and lower type bounds.

    class UpperTypeBound
    def functionName[T <: UpperTypeBound](param: T) = ???
    
    class LowerTypeBound
    def functionName[T >: LowerTypeBound](param: T) = ???
    

    In your case, you have something like

    case class Comparable[T]()
    case class Statistics[T <: Comparable[T]]()
    

    to make your method have a type parameter T with an upper bound type of Comparable[T], you should have to do something like

      def getMinMaxAsString[T <: Comparable[T]](stats: Statistics[T]): (Option[String], Option[String]) = {
        (Some(""), Some(""))
      }
    

    As you can see, the type parameter is defined before the parameters values and you can type the paremeter values with the type parameter you declare