Search code examples
scalatype-parameterabstract-methods

Scala error implementing abstract method with type parameter


to make it short, this works:

object Main {
  def main(args: Array[String]) {
    trait T1[T] {
      def f1(a: T): Double
    }

    val ea1 = new T1[List[String]] {
      def f1(a: List[String]): Double = a.length
    }
  }
}

But this won't compile:

object Main {
  def main(args: Array[String]) {
    trait T1 {
      def f1[T](a: T): Double
    }

    val ea1 = new T1 {
      def f1(a: List[String]): Double = a.length
    }
  }
}

object creation impossible, since method f1 in trait T1 of type [T](a: T)Double is not defined
    val ea1 = new T1 {
              ^

It seems like the method is not taken into account because of type parameter on method.

How can I achieve this without using trait type parameters or trait abstract types?! TIA!


Solution

  • You may want to define a type T to do away with Trait Type Parameters and accomplish the same as..

        trait T1 {
          type T
          def f1(a: T): Double
        }
    
        val ea1 = new T1 {
           type T = List[String]
           def f1(a: T): Double = a.length
        }                                            
    
        ea1.f1(List("1","2"))  
        // res0: Double = 2.0