English 中文(简体)
这两者之间有什么差别?
原标题:What s the difference between these two calls to a function taking a collection of structural types?

为什么要编造假(Iterator(“foo”),但打耳机(fooIterator)的电话却有误,“

object Qx {
    type HasLength = {def length: Int}
    def fn(xs: Iterator[HasLength]) = 3
    var tn = fn(Iterator("foo"))
    var fooIterator = Iterator("foo")
    var tnFails = fn(fooIterator) //doesn t compile
}

更不用说什么?

最佳回答

这必须成为改进的体现,因为以下两条表述都是工作。

object Qx1 {
    // give length() parens, even though the Iterator definition doesn t have them
    type HasLength = { def length(): Int }

    def fn(xs: Iterator[HasLength]) = 3
    var tn = fn(Iterator("foo"))
    var fooIterator = Iterator("foo")
    var tnFails = fn(fooIterator) //doesn t compile
}

object Qx2 {
    type HasLength = { def length: Int }

    def fn(xs: Iterator[HasLength]) = 3
    var tn = fn(Iterator("foo"))
    // annotate the type of fooIterator before the type inferencer can mis-infer
    var fooIterator: Iterator[HasLength] = Iterator("foo")
    var tnFails = fn(fooIterator) //doesn t compile
}

Edit:

上午太早。 这套方法有长处,这意味着它正确,而且你在思考时间长度和时间长度方面有错误。 (这只剩下一个小小小小块的陷阱,在前有记载。)

问题回答

这一表述有助于:

object Qx {
    type HasLength = {def length: Int}
    def fn[HL <% HasLength](xs: Iterator[HL]) = 3
    val tn = fn(Iterator("foo"))
    val fooIterator = Iterator("foo")
    val tnFails = fn(fooIterator)
}




相关问题
How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

To use or not to use Scala for new Java projects? [closed]

I m impressed with Twitter and investigating to use Scala for a new large scale web project with Hibernate and Wicket. What do you think about Scala, and should I use it instead of Java? EDIT: And, ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Include jar file in Scala interpreter

Is it possible to include a jar file run running the Scala interpreter? My code is working when I compile from scalac: scalac script.scala -classpath *.jar But I would like to be able to include a ...

Scala and tail recursion

There are various answers on Stack Overflow which explain the conditions under which tail recursion is possible in Scala. I understand the limitations and how and where I can take advantage of tail ...

热门标签