2012-08-11 53 views
6

Mientras escribía algunos códigos Scala, recibí un extraño mensaje de error cuando intentaba compilar el código. Desglose el código a uno mucho más simple (que no tiene ningún sentido desde el punto de vista semántico, pero aún muestra el error).Extraño error al compilar un bucle for

scala> :paste 
// Entering paste mode (ctrl-D to finish) 

import scala.collection.mutable.ListBuffer 

val map = scala.collection.mutable.Map[Int, ListBuffer[Int]]() 
for (i <- 1 to 2) { 
    map.get(0) match { 
    case None => map += (1 -> ListBuffer[Int](1)) 
    case Some(l: ListBuffer[Int]) => l += i 
    } 
} 

// Exiting paste mode, now interpreting. 

<console>:12: error: type arguments [Any] do not conform to trait Cloneable's t 
pe parameter bounds [+A <: AnyRef] 
       for (i <- 1 to 2) { 
         ^

Al agregar una línea adicional al final del bucle, el código funciona:

scala> :paste 
// Entering paste mode (ctrl-D to finish) 

import scala.collection.mutable.ListBuffer 

val map = scala.collection.mutable.Map[Int, ListBuffer[Int]]() 
for (i <- 1 to 2) { 
    map.get(0) match { 
    case None => map += (1 -> ListBuffer[Int](1)) 
    case Some(l: ListBuffer[Int]) => l += i 
    } 
    1 // <- With this line it works 
} 

// Exiting paste mode, now interpreting. 

warning: there were 1 unchecked warnings; re-run with -unchecked for details 
import scala.collection.mutable.ListBuffer 
map: scala.collection.mutable.Map[Int,scala.collection.mutable.ListBuffer[Int]] 
= Map(1 -> ListBuffer(1)) 

supongo, que tiene algo que ver con el valor de retorno del partido-sentencia-case . Pero no soy lo suficientemente experto en Scala para descubrir la razón detrás de este mensaje de error y lo que estoy haciendo mal. Espero que alguien más sabio pueda ayudar aquí.

¿Cuál es la razón detrás del mensaje de error? ¿Qué está mal con el enunciado de la caja de fósforos?

ACTUALIZACIÓN: Probado con Scala 2.9.2

+0

Esto es probablemente un error. Con 2.10 funciona bien. – sschaef

Respuesta

6

Estás viendo this bug en acción. Se fija en 2,10, y hay una solución fácil en this answer -JUST añadir una anotación de tipo alguna parte:

for (i <- 1 to 2) { 
    map.get(0) match { 
    case None => map += (1 -> ListBuffer[Int](1)) 
    case Some(l: ListBuffer[Int]) => (l += i): Unit 
    } 
} 
+0

Muchas gracias para señalar esto. –