String literal is not interpreted as type String

I am trying to implement a simple subclass Iterable[String]

and I am running into something that seems a little strange to me. My code looks like this:

class ItString[String] extends Iterable[String]{
    override def iterator: Iterator[String] = new Iterator[String] {
        def hasNext = true
        def next = "/"
    }
}

      

My IDE complains that it expects String

but is actually of a type String

, and when I try to compile it further shows that the problem is that it requires it String

, but that the literal is indeed of a type java.lang.String

. Now I can fix this by changing it to "/".asInstanceOf[String]

, but I would like to know why Scala does not recognize the type correctly.

+3


source to share


1 answer


So how can I get the following to compile:

class ItString extends Iterable[String] {
  override def iterator: Iterator[String] = new Iterator[String] {
    def hasNext = true
    def next = "/"
  }
}

      

I can assume your problem is with the writing:



class ItString[String] extends ...

      

What happens is that this event is String

not type- java.lang.String

specific, but it is an unknown parameterized type (for example, T

or A

). So when you write [String]

it means some unknown type, which will be determined by the implementation class, not the type String

you intended.

+5


source







All Articles