【问题标题】:Trailing comma in a type类型中的尾随逗号
【发布时间】:2014-01-19 01:38:48
【问题描述】:

下面的类型到底是什么:

(Int, => Double) => String

注意Int 后面的逗号。显然这不是句法漏洞,而是不同于

(Int => Double) => String

例如使用重载时:

trait Foo {
  def bar(x: (Int, => Double) => String): Unit
  def bar(x: (Int  => Double) => String): Unit
}

【问题讨论】:

  • 为什么你认为它是一个尾随逗号而不是分隔符?
  • 好问题,我想你需要问一个格式塔理论家......

标签: scala types


【解决方案1】:

(Int, => Double) => String 是一个带有第二个参数的函数 (=> Double)。

你不能创建一个Function2[Int, => Double, String],但是你可以创建一个lambda (Int, => Double) => String,意思是一样的:

scala> def s:(Int, => Double) => String =
     |   (a, b) => if (a > 0) a.toString else b.toString
s: (Int, => Double) => String

scala> s(1, {println("test"); 2.0}) //second parameter is not evaluated
res0: String = 1

scala> s(-1, {println("test"); 2.0})
test
res1: String = 2.0

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 2018-01-10
    • 2021-01-25
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 2021-06-05
    相关资源
    最近更新 更多