【问题标题】:Scala: Option, Some and the ArrowAssoc operatorScala:Option、Some 和 ArrowAssoc 运算符
【发布时间】:2015-11-22 02:34:48
【问题描述】:

我正在尝试分析以下 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 所扮演的角色。

【问题讨论】:

  • 我认为除了使用逗号代替-> 之外,没有更好的表达方式。为什么要导入scala.Some?过度热心的 IDE?

标签: scala


【解决方案1】:

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

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

相当于

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

我只是想添加源代码,但 Reactormonk 已经先到了;-)

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

【讨论】:

  • 我将接受您的答案作为正确答案,因为您确实说过返回类型是什么。 @ReactorMonk 的回答也不错。
  • 非常感谢。两个答案在目标上都同样正确。我很感激
【解决方案2】:

-> 运算符的常见情况是

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

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

因为Map.apply 的签名有效,所以是

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

这意味着它将元组作为参数并构造一个Map from 它。

所以

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

【讨论】:

  • 我有点困惑。 @Dan 说, -> 运算符创建了一个元组。在您给出的地图示例中,1 ->“食物”,键值对是一个元组,人们通过它来创建地图?
  • 非常感谢。您的回答非常详细,并且达到了目标。在寻求有关元组的澄清后,您添加了更多上下文,并在@Dan 回答后巩固了我的理解。
猜你喜欢
  • 1970-01-01
  • 2015-07-16
  • 2019-07-30
  • 2022-12-08
  • 2012-11-26
  • 2014-08-07
  • 2021-11-21
  • 2020-01-25
  • 2016-02-19
相关资源
最近更新 更多