Implementation of polymorphic interface

Hi all,

For a home assignment, I must define a polymorphic interface and its implementation.
The interface is below :
trait SortService[T] {
def sortData[T](l: List[T]): List[T]
def isSorted[T](l: List[T]): Boolean
}

So far, so good.

The problem occurred when I tried to write the implementation.
I though of something like
object SortServiceImplementation[T] extends SortService[T] {
def sortData[T](l: List[T]): List[T] = {

}
}
The specific part "object SortServiceImplementation[T] extends SortService[T] " is not accepted by the compiler.
object SortServiceImplementation extends SortService[Int] {

}
is ok but the functions inside SortServiceImplementation are, thus, not polymorphic.

Is there a syntactically correct way of implementing an interface with polymorphic functions or interfaces just can’t be implemented in a polymorphic way.

Hoping my question is clear enough :wink:

TIA

a literal object can’t have a type parameter – it’s type must be fully known at creation time.

I suspect that your assignment may involve defining implicit implementations of SortService which are injected by the compiler as needed. For example:

object SortService {

implicit object IntSortService extends SortService[Int] { … }

implicit object StringSortService extends SortService[String] { … }

etc.

}

//-- at place a SortService is needed

import com.whatever.SortService._

def sortMyList[T](l: List[T])(implicit ss: SortService[T]): List[T] = ss.sortData(l)

sortMyList(List(4, 3, 6, 7))

sortMyList(List(“This”, “is”, “a”, “list”))

Brian Maso

There is something I don’t get in your trait.
Why having both a type parameter for the trait and for the methods?

If you keep the methods polymorphic (by adding [T] next to their name), then the T parameter of the trait doesn’t seem to be useful in your case.

Now, generally speaking, if you keep the trait parameterized by T, then you can either :

  • implement the trait for a fixed choice of T (using an object, and a concrete type, say Int)
  • implement the trait (mostly) independently of T, but then you should use a class parameterized by a type.

Best,
D.

Thanks for the answers.

Why having both a type parameter for the trait and for the methods?

Yes, this is mistaken in the first place.

a literal object can’t have a type parameter – it’s type must be fully known at creation time.

Understood.

I suspect that your assignment may involve defining implicit implementations of SortService

In fact not. I made it more complex that it was supposed to be.
Thanks for your help.

A.B.