当评估Option的数据时,我试图使用fold[B](ifEmpty: => B)(f: A => B): B
,但我对结果有点困惑:
scala> Some(1).fold(() => "empty")(d => d.toString) res5: () => String =scala> Some(1).fold(() => "empty")(d => d.toString)() res6: String = 1
这个方法的源代码:
@inline final def fold[B](ifEmpty: => B)(f: A => B): B = if (isEmpty) ifEmpty else f(this.get)
我预计结果是String
,但得到了
,为什么?
==================
我尝试使用以下代码模拟这种情况:
case class Demo(size: Int) // version 1, with the same fold method as Option case class X [A <: Demo](data: A) { def fold[B](ifEmpty: => B)(f: A => B): B = { if(data.size < 3) ifEmpty else f(data) } } val demo = Demo(2) val x = X(demo) x.fold(() => "empty")(d => d.toString) // the result is a function // version 2 case class X [A <: Demo](data: A) { def fold[B](g: A => B)(f: A => B): B = { if(data.size < 3) g(data) else f(data) } } x.fold(g => g.toString)(f => f.toString) // the result is a String
根据演示,似乎结果受到scala类型推断的影响,是吗?