Domanda

I'm trying to extend the List class to give it some more streamlined way to compare the sizes, however I run into the error in the title...

Here's my code:

implicit class RichList[A, B](input: List[A]) {
  def >(that: List[B]): Boolean = input.size > that.size
  def <(that: List[B]): Boolean = input.size < that.size
}

The idea was that since all it does it compare the sizes of the lists, their types could be different and it wouldn't matter, however when I try to do this:

val test = List(1,2,3,4) < List(1,2,3,4,5)

I get the beforementioned error. If I remove B and set that to be of type List[A] it works fine, but then I wouldn't be able to use lists containing 2 different types...

Why is it that both A and B can't be the same type? Or am I missing something?

Edit: Ok I've found a solution to the error, which is rather simple:

implicit class RichList[A](input: List[A]) {
  def >[B](that: List[B]): Boolean = input.size > that.size
  def <[B](that: List[B]): Boolean = input.size < that.size
}

However my question still stands; why can't I do it the other way?

È stato utile?

Soluzione

In your helper class you define the type B in the class initialization. But that type is unknown until the method > or < usage.

My solution would be this.

implicit class RichList[A](input: List[A]) {
  def >[B](that: List[B]): Boolean = input.size > that.size
  def <[B](that: List[B]): Boolean = input.size < that.size
}

Edit

Since you asked, why its not possible in other way, consider following example.

List(1,2,3) > List("1", "2")

We hope this will implicitly expand to (This wont happen)

new RichList[Int, B](List[Int](1,2,3)).>(List[String]("1", "2"))

But, type B is not resolved to String. Therefore, compiler neglects this implicit conversion, and gives a compilation error.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top