开发者

Scala anonymous class type mismatch

I am creating a list holding Comparable objects and wish to create one object that serves as the minimum of the list, such that it always returns -1 for its compareTo method. Other methods in the list, like print here requires an input of type A. If I compile the code I get the following error:

error: type mismatch;
found   : java.lang.Object with java.lang.Comparable[String]
required: String
l.print(l.min)

Anyone have any idea about how can a create such a minimum element so that it is always smaller than any other elements in the list?

class MyList[A <: Comparable[A]] {开发者_如何转开发
  val min = new Comparable[A] {
    def compareTo(other: A) = -1
  }

  def print(a: A) = {
    println(a)
  }
}

class Run extends Application {
  val l = new MyList[String]
  l.print(l.min)
}


Well, the input passed is not equal to the input provided, right? print needs an A:

def print(a: A) = {

And min does not return an A:

val min = new Comparable[A] {

As to creating such an A as you want it... how could you possibly go about it? You don't know anything about A -- you don't know what its toString returns, you don't know what methods it implements, etc.

So, basically, change your algorithm.


You are getting a compile error because you're trying to use a Comparable where the compiler is expecting a A, what you really want to do is:

  val min: A = new A {
    def compareTo(other: A) = -1
  }

but you can't do this in Scala (or Java), because you're trying to create an object of an unknown type (A). You could do this using reflection, but you would still have the problem of creating an object which was less than any other object in the list.

Also, be aware that your implementation of compareTo will have problems with almost any sorting algorithm you choose, because you can't guarantee compareTo is always called from min. For example, you could get:

min.compareTo(list(0)) // returns -1
list(0).compareTo(min) // could be anything really

If you want a list that returns a specific object as the 'minimum' then you could just prepend a specific value to the sorted list:

class MyList2[A <: Comparable[A]] {
    val min: A; // somehow create an instance of the class A
    val list: List[A]

    def sort(fn: (A, A) => Boolean) = {
        min :: list.sort(fn)
    }
}

but as Daniel says, this is probably the wrong way to go about it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜