Scala运算符#>导致编译错误,但无法&> - 为什么? [英] Scala operator #> causes compilation error but not &> - why?

查看:178
本文介绍了Scala运算符#>导致编译错误,但无法&> - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型推理问题,并要求帮助此处
最初的问题是由于重载。一旦纠正I
仍然有问题。

I have a type inference issue and asked for help here. The initial problem was due to overload. Once corrected I still had problems.

这里是代码:

class DPipe[ A ]( a: A ) {
  def !>[ B ]( f: A => B ) = Try(f( a ))
  def #>[ B, C ]( f: B => C )(implicit ev: A =:= Try[B]) : Try[C] = a.map(f)
  //def &>[ B, C ]( f: B => C )( implicit ev: A =:= Try[ B ] ) =  a.map( f )
}

object DPipe {
  def apply[ A ]( v: A ) = new DPipe( v )
}

object DPipeOps {
  implicit def toDPipe[ A ]( a: A ): DPipe[ A ] = DPipe( a )
}

这里是测试:

object DPipeDebug {

 def main( args: Array[ String ] ) {

    import DPipeOps._

    val r8 = 100.0 !> {x : Double => x / 0.0}  
    println(r8)
    val r9 = r8 #> {x:Double => x* 3.0} 
    println(r9)
    /*
    val r8 = 100.0 !> { x: Double => x / 0.0 }
    println( r8.get )
    val r9 = r8 &> { x: Double => x * 3.0 }
    println( r9 )*/

    val r10 = (100.0 !> {x : Double => x / 0.0}) #> {x:Double => x* 3.0} 
   //val r10 = ( 100.0 !> { x: Double => x / 0.0 } ) &> { x: Double => x * 3.0 }

    val r11 = 100.0 !> {x : Double => x / 0.0} #> {x:Double => x* 3.0} 
    //val r11 = 100.0 !> { x: Double => x / 0.0 } &> { x: Double => x * 3.0     }
  }

}

我们在最后一行代码中有以下错误:

As it stands we have the following error in the last code line:

Cannot prove that Double => Double =:= scala.util.Try[Double].
val r11 = 100.0 !> {x : Double => x / 0.0} #> {x:Double => x* 3.0} 
                                           ^

请注意,在第二个代码行中,添加
圆括号以强制执行左侧左侧相关性
(Scala默认值)。看起来像#> 运算符尝试
使用函数 {x:Double => x / 0.0} ,这的确是一个
Double。

Notice that in the second last code line, I need only add the parenthesis to enforce left left-hand associativity (Scala default). It seems like the #> operator tries to use the function {x : Double => x / 0.0}, which indeed is a Double.

但是,如果我使用&>运算符,则不会发生错误。在下面的
测试代码中,只需翻转注释。所以我的问题是,为什么
是这种情况发生。这是Scala 2.12.0的新功能吗?

If however I use the "&>" operator, no error occurs. In the test code below, just flip the comments. So my question is, why is this happening. Is this something new to Scala 2.12.0?

TIA

推荐答案

问题是与运算符优先级。以下是更多详细信息: Scala中的运算符优先级

The problem is with the operator precedence. Here are more details: Operator precedence in Scala

这取决于运算符的第一个字符。 的优先级高于&

It depends on the first character of the operator. # has higher precedence than ! and ! has higher precedence than &.

因此您会得到

100.0 !> ({x : Double => x / 0.0} #> {x:Double => x* 3.0})


b $ b

而不是

instead of

(100.0 !> {x : Double => x / 0.0}) #> {x:Double => x* 3.0}

这篇关于Scala运算符#>导致编译错误,但无法&> - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆