Why can't this simple scala example be compile

2019-09-04 16:37发布

问题:

class X extends Map[String, String] {
    def x(): X = { X() } // can't be compiled
}

can't be compiled, the error is:

<console>:6: error: not found: value X
def x(): X = { X() } // can't be compiled

Why is X not found? I can't see how to correct it.


UPDATE:

I know the reason now. What I want to do is create a class which extends HashMap, since Map() will return an instance of HashMap, so I thought I can just extends Map. Now, the correct code should be:

import scala.collection.immutable.HashMap
class X extends HashMap[String, String] {
    def x(): X = { new X() }
}

回答1:

Try new X() instead of X() -- you'll get another error, but it'll set you on the right track I believe.

In the latter case it is trying to invoke apply upon the expression denoted by X (e.g. imagine where X is defined as object X or val X) and not trying to invoke the constructor for class X.

Happy coding.



回答2:

Can I recommend that you try a different approach?

Extending the collection library is one of the more advanced things you can do in Scala. To do the job properly you need a deep understanding of higher-kinded types, inference, variance, implicits, and the CanBuildFrom mechanism. This is not a light-hearted task to be taken on by a beginner.

On the other hand, it's incredibly rare that you'll ever actually need to extend a collection.

Go back to first principles... What problem are you trying to solve for which you think the correct approach is to extend HashMap? I can virtually guarantee that there's a much better way to do it in Scala.

UPDATE Mk.II

This answer previously contained a description of the collection framework CanBuildFrom logic. Following @soc's suggestion, I've now migrated that part of the answer to an FAQ question here



回答3:

It's not clear what you are trying to do, but the reason it doesn't compile is that there is no field, function or method called 'X', and there is no module 'X' with an 'apply()' method.

"How to correct it?"

Clarify what you are trying to achieve.



标签: scala