2015-03-31 12 views
1

我試圖分析下面的一段Scala代碼:斯卡拉:選項,有的和ArrowAssoc操作

import java.nio.file._ 
import scala.Some 

abstract class MyCustomDirectoryIterator[T](path:Path,someNumber:Int, anotherNum:Int) extends Iterator[T] { 

def getCustomIterator(myPath:Path):Option[(DirectoryStream[Path], 
               Iterator[Path])] = try { 
    //we get the directory stream   
    val str = Files.newDirectoryStream(myPath) 
    //then we get the iterator out of the stream 
    val iter = str.iterator() 
    Some((str -> iter)) 
    } catch { 
    case de:DirectoryIteratorException => 
     printstacktrace(de.getMessage) 
     None 

    } 

如何interpert這段代碼:Some((str -> iter)) 是的,它返回類型的值:

Option[(DirectoryStream[Path], Iterator[Path])] 

- >運算符是,盡我的理解,ArrowAssoc從scala.Predef包。

implicit final class ArrowAssoc[A] extends AnyVal 

但我還是不明白什麼 - >東西是做給我類型的返回值:

Option[(DirectoryStream[Path], Iterator[Path])] 

Scala的專家在這裏能投入更多的光對此有何看法?有沒有辦法以更可讀的方式編寫「一些(..)」的東西?不過,我理解Some的作用。

+0

我不認爲有任何更好的表達方式,除了使用逗號而不是' - >'。爲什麼地球上是'scala.Some'被導入?過度的IDE? – 2015-03-31 21:54:50

回答

5

->操作只是創建一個元組:

scala> 1 -> "one" 
res0: (Int, String) = (1,one) 

這相當於

scala> (1, "one") 
res1: (Int, String) = (1,one) 

我只是要添加的源代碼,但Reactormonk已經到了那裏第一;-)

->方法可通過隱式ArrowAssoc類在任何對象上使用。在類型爲A的對象上調用它,傳遞類型B的參數,將創建Tuple2[A, B]

+0

我會接受你的答案作爲正確的答案,因爲你確實說過返回類型是什麼。 How @ ReactorMonk的回答很不錯。 – user3825558 2015-03-31 19:28:44

+0

非常感謝。兩個答案在目標上都是一樣的。我很感激 – user3825558 2015-03-31 19:43:56

6

通常情況下爲->運營商

Map(1 -> "foo", 2 -> "bar") 

這是一樣的

Map((1, "foo"), (2, "bar")) 

其中一期工程,因爲Map.apply簽名

def apply[A, B](elems: Tuple2[A, B]*): Map[A, B] 

,這意味着它需要元組作爲參數並構造Map從 它。

所以

(1 -> "foo") 

相當於

(1, "foo") 

從編譯來源:

implicit final class ArrowAssoc[A](private val self: A) extends AnyVal { 
    @inline def -> [B](y: B): Tuple2[A, B] = Tuple2(self, y) 
    def →[B](y: B): Tuple2[A, B] = ->(y) 
} 

告訴你直接它創建一個元組。而那1 → "foo"也適用。

+0

我有點困惑。 @丹說, - >運算符創建一個元組。在你給出的地圖例子中,1 - >「食物」,關鍵值對是一個通過創建Map的元組? – user3825558 2015-03-31 19:30:47

+0

非常感謝。你的回答非常詳細,並達到目標的標誌。在尋求關於元組的澄清之後,您添加了更多的上下文,並在@Dan回答後鞏固了我的理解。 – user3825558 2015-03-31 19:43:14