2015-03-31 36 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