This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Confusing type mismatch error

3 replies
Nathan Gz Fang
Joined: 2011-05-09,
User offline. Last seen 42 years 45 weeks ago.
Hi all,
I have just started to learn scala, so please forgive my ignorance if this looks naive. Here is the code:
trait tr { def foo(t: String) = println(t) }
class AbstractClass {  def bar[U](a: U)}
class ConcreteClass extends AbstractClass with tr {  override def bar[String](a: String) = foo(a)                     // type mismatch; found : String(in method bar) required: java.lang.String}
I don't understand why there is a type mismatch here. I'm using the scala plugin for eclipse, and can someone explain what does the error message mean? what is String(in method bar)?
Sam Reid
Joined: 2011-05-09,
User offline. Last seen 42 years 45 weeks ago.
Re: Confusing type mismatch error
I saw someone else have the same problem during our Scala workshop in Boulder last week.  The problem is that in override def bar[String], the name String is just a type name for an arbitrary type (like T or U).  It collides with the Predef type name for String, so the compiler throws it out.  I've written your code to require a subtype of String and renamed String=>X in ConcreteClass.

trait tr {def foo(t: String) = println(t)}

abstract class AbstractClass {
  def bar[U <: String](a: U)
}

class ConcreteClass extends AbstractClass with tr {
  override def bar[X <: String](a: X) = foo(a)
}

object Tester {
  def main(args: Array[String]) {
    new ConcreteClass().bar("hello")
  }
}
//Prints "hello"
Todd Vierling
Joined: 2011-04-27,
User offline. Last seen 42 years 45 weeks ago.
Re: Confusing type mismatch error
On Monday, May 9, 2011 12:31:33 AM UTC-4, samreid wrote:
trait tr {def foo(t: String) = println(t)}

abstract class AbstractClass {
  def bar[U <: String](a: U)
}

class ConcreteClass extends AbstractClass with tr {
  override def bar[X <: String](a: X) = foo(a)
}

Similar code follows, which (I have a feeling) may be more appropriate depending on the context. It's probably more likely that the desire is to have the type declaration apply to all methods using that type:
abstract class AbstractClass[U] {  def bar(a: U)}
class ConcreteClass extends AbstractClass[String] with tr {  override def bar(a: String) = foo(a)}
Nathan Gz Fang
Joined: 2011-05-09,
User offline. Last seen 42 years 45 weeks ago.
Re: Confusing type mismatch error

Thank you very much for the prompt replies.I also find this post very helpful :)

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland