Scala:Option,Some和ArrowAssoc运算符

时间:2015-03-31 19:20:24

标签: scala

我正在尝试分析以下Scala代码:

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

  }

我如何插入这段代码:Some((str -> iter)) 是的,它返回的值为:

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

- >从我的理解来看,运算符是来自scala.Predef包的ArrowAssoc。

implicit final class ArrowAssoc[A] extends AnyVal

但我仍然不明白 - >事情是给我一个类型的返回值:

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

这里的Scala专家能否更多地了解这一点?有没有办法以更易读的方式编写“Some(..)”的东西?不过,我确实理解了Some扮演的角色。

2 个答案:

答案 0 :(得分:8)

->运算符只创建一个元组:

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

相当于

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

我只是要添加源代码,但Reactormonk首先到达那里;-)

->方法通过隐式ArrowAssoc类在任何对象上可用。在A类型的对象上调用它,传递B类型的参数,会创建Tuple2[A, B]

答案 1 :(得分:8)

->运算符的常见情况是

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"也可以。

相关问题