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

Wierd type mismatch errors, whats going on here?

2 replies
Pooria Mellati
Joined: 2011-03-31,
User offline. Last seen 42 years 45 weeks ago.
Hi,

Three lines of code:

scala> var lol = List.empty[List[AnyRef]]
lol: List[List[AnyRef]] = List()

scala> var data = List(2,3,4).map {_.asInstanceOf[AnyRef]}
data: List[AnyRef] = List(2, 3, 4)

scala> lol += data
<console>:8: error: type mismatch;
 found   : List[AnyRef]
 required: String
       lol += data
              ^

Which is wierd, because in the above code I haven't said anything about "String"s at all.
Now, strangely, if I try to feed an actual String into "lol", I get the correct type of error:

scala> lol += "agadsf"
<console>:7: error: type mismatch;
 found   : java.lang.String
 required: List[scala.List[AnyRef]]
       lol += "agadsf"
           ^

What am I doing wrong here?

Thanks.
Alex Cruise
Joined: 2008-12-17,
User offline. Last seen 2 years 26 weeks ago.
Re: Wierd type mismatch errors, whats going on here?
On Thu, Mar 31, 2011 at 1:14 PM, Pooria Mellati <ac.pooria@gmail.com> wrote:
Hi,

Three lines of code:

scala> var lol = List.empty[List[AnyRef]]
lol: List[List[AnyRef]] = List()

scala> var data = List(2,3,4).map {_.asInstanceOf[AnyRef]}
data: List[AnyRef] = List(2, 3, 4)

scala> lol += data
<console>:8: error: type mismatch;
 found   : List[AnyRef]
 required: String
       lol += data
              ^

Which is wierd, because in the above code I haven't said anything about "String"s at all.
Now, strangely, if I try to feed an actual String into "lol", I get the correct type of error:

The + "operator" is special and best avoided except when you're dealing with numeric values or string-like values.  
More here: http://stackoverflow.com/questions/2664274/how-to-unimport-string-operator-in-scala
-0xe1a
Derek Williams
Joined: 2009-06-13,
User offline. Last seen 42 years 45 weeks ago.
Re: Wierd type mismatch errors, whats going on here?

On Thu, Mar 31, 2011 at 2:14 PM, Pooria Mellati wrote:
> What am I doing wrong here?

List does not have a + method, The correct method is :+

lol :+= data

see: http://www.scala-lang.org/api/current/scala/collection/immutable/List.html

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