Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String literal not interpreted as type String

Tags:

string

scala

I'm trying to implement a simple subclass of Iterable[String], and I'm encountering something that seems a bit strange to me. My code is as follows:

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

My IDE complains that it's expecting a String but it's actually of type String, and when trying to compile, it further reveals that the problem is that it requires String but that the literal is actually of type java.lang.String. Now, I can fix this by changing it to "/".asInstanceOf[String], but I'd like to know why Scala isn't recognising the type correctly.

like image 756
childofsoong Avatar asked Nov 29 '25 23:11

childofsoong


1 Answers

Since I can 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 deduce that your problem is with writing:

class ItString[String] extends ...

What's going on is that this occurrence of String doesn't refer to the type java.lang.String, but it is instead an unknown parameterised type (like T or A). So, when you write [String], this means some unknown type that will be determined by the implementing class rather than the String type that you intended.

like image 118
Hugo Sereno Ferreira Avatar answered Dec 01 '25 14:12

Hugo Sereno Ferreira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!