Scala 匿名类类型不匹配
我正在创建一个包含 Comparable
对象的列表,并希望创建一个作为列表中最小值的对象,这样它的 compareTo
方法始终返回 -1。列表中的其他方法,例如这里的 print
需要类型 A 的输入。如果我编译代码,我会收到以下错误:
error: type mismatch;
found : java.lang.Object with java.lang.Comparable[String]
required: String
l.print(l.min)
任何人都知道如何创建这样一个最小元素,以便它总是小于列表中的任何其他元素?
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)
}
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)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那么,传递的输入不等于提供的输入,对吧?
print
需要一个A
:而
min
不会返回A
:至于创建这样一个
A
如你所愿...你怎么可能这么做呢?你对A
一无所知——你不知道它的toString
返回什么,你不知道它实现了什么方法,等等。所以,基本上,改变你的算法。
Well, the input passed is not equal to the input provided, right?
print
needs anA
:And
min
does not return anA
:As to creating such an
A
as you want it... how could you possibly go about it? You don't know anything aboutA
-- you don't know what itstoString
returns, you don't know what methods it implements, etc.So, basically, change your algorithm.
您收到编译错误,因为您尝试在编译器期望 A 的情况下使用 Comparable,您真正想要做的是:
但您不能在 Scala(或 Java)中执行此操作),因为您正在尝试创建未知类型 (A) 的对象。您可以使用反射来做到这一点,但是您仍然会遇到创建一个小于列表中任何其他对象的对象的问题。
另外,请注意,您的compareTo 实现对于您选择的几乎所有排序算法都会出现问题,因为您不能保证compareTo 始终从min 调用。例如,您可以获得:
如果您想要一个返回特定对象作为“最小值”的列表,那么您可以在排序列表前面添加一个特定值:
但正如丹尼尔所说,这可能是错误的方法。
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:
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:
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:
but as Daniel says, this is probably the wrong way to go about it.