2011-02-08 20 views
7

w poniższym kodzie wewnątrz for zrozumienia, że ​​może odnosić się do napisu i indeksu za pomocą dereference krotka:Scala za-pojmowania składni

val strings = List("a", "b", "c") 
for (stringWithIndex <- strings.zipWithIndex) { 
    // Do something with stringWithIndex._1 (string) and stringWithIndex._2 (index) 
} 

Czy istnieje jakiś sposób, w składni Scala mieć stringWithIndex podzielone na części (ciąg i indeks) w nagłówku for ze zrozumieniem, aby czytelnicy kodu nie musieli się zastanawiać nad wartościami stringWithIndex._1 i stringWithIndex._2?

Próbowałem następujących, ale nie byłoby skompilować:

for (case (string, index) <- strings.zipWithIndex) { 
    // Do something with string and index 
} 

Odpowiedz

21

Prawie got it:

scala> val strings = List("a", "b", "c") 
strings: List[java.lang.String] = List(a, b, c) 

scala> for ((string, index) <- strings.zipWithIndex) 
     | { println("str: "+string + " idx: "+index) } 
str: a idx: 0 
str: b idx: 1 
str: c idx: 2 

Patrz, nie ma potrzeby case hasła.

+1

Doh! Powinienem tego spróbować :-). – Ralph

7
strings.zipWithIndex.foreach{case(x,y) => println(x,y)} 

res:

(a,0) 
(b,1) 
(c,2) 
+0

Niezupełnie to, czego potrzebowałem, ale fajny przepis, nie mniej. – Ralph

+2

Chociaż dla tego wyjścia, pojedyncze 'foreach (println)' byłoby już wystarczające ... – Debilski

Powiązane problemy