Search code examples
scalatype-parameter

Scala: avoiding redundant type parameters


Suppose I have an abstract class Bar that takes a type parameter:

abstract class Bar[A] { def get: A } 

and I have a function that wants to instantiate some Bar objects, call their get methods and return the results:

def foo[A, B <: Bar[A]]: Seq[A]

It seems a little verbose to have to provide A as a separate type parameter, since it's implicit in B. What I would really like is to say

def foo[B <: Bar[A]]: Seq[A]

but that doesn't compile. Is there a way to make foo more compact?


Solution

  • What Daniel said in the comment.

    Perhaps using an abstract type member will help reduce the verbosity.

    abstract class Bar { 
      type A
      def get: A 
    } 
    
    def foo[B <: Bar]: Seq[B#A]
    def baz[B <: Bar](b: B): Seq[B#A]
    def taz[B <: Bar](b: B): Seq[b.A]