使用占位符语法的选择如何进行类型推断?

时间:2018-10-10 20:15:58

标签: scala

我正在阅读《 Scala中的Functional Programming》一书中的练习中的一些代码示例(但我的问题与FP不相关)。 https://github.com/fpinscala/fpinscala/blob/master/answers/src/main/scala/fpinscala/state/State.scala

我有一个关于以下行的Scala语法问题:

val int: Rand[Int] = _.nextInt

此摘录:

trait RNG {
  def nextInt: (Int, RNG) // Should generate a random `Int`. We'll later define other functions in terms of `nextInt`.
}

object RNG {

  case class Simple(seed: Long) extends RNG {
    def nextInt: (Int, RNG) = {
      val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL // `&` is bitwise AND. We use the current seed to generate a new seed.
      val nextRNG = Simple(newSeed) // The next state, which is an `RNG` instance created from the new seed.
      val n = (newSeed >>> 16).toInt // `>>>` is right binary shift with zero fill. The value `n` is our new pseudo-random integer.
      (n, nextRNG) // The return value is a tuple containing both a pseudo-random integer and the next `RNG` state.
    }
  }

  type Rand[+A] = RNG => (A, RNG)

  val int: Rand[Int] = _.nextInt
}

下划线在这里指的是什么?在这种情况下,int甚至是什么?它只是一个函数,特别是nextInt吗?但是如果是这样,下划线如何指向该功能?

1 个答案:

答案 0 :(得分:5)

这是普通的function placeholder syntax

_.nextInt

相同
(_: RNG).nextInt

又与

相同
(rng: RNG) => rng.nextInt

因此,int是一个函数,该函数以RNG作为参数,并通过调用方法{{1}返回IntRNG的新状态。 }}。


更新

编译器可以将nextInt扩展为_,因为您已经在分配的左侧明确指定了预期的类型:

(_: RNG)

相同
val int: Rand[Int] = ...

相同
val int: RNG => (Int, RNG) = ...

以及类型参数val int: Function1[RNG, (Int, RNG)] = ... RNG不必在右侧重复提及。


下划线占位符语法的其他用法:

  1. println(_)