Scala中缺少类型运算符的参数类型

Scala中缺少类型运算符的参数类型

本文介绍了Scala中缺少类型运算符的参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  class Pipe [A](a:A){
def | > [B](f:A => B)= f(a)
def! ))
def!> [B,C](f:B => C)(implicit ev:A =:= Try [B]):Try [C] = a.map(f)
}

(隐含且不适用)



我对missing parameter type错误有问题。
以下代码正确编译:

  val r1 = 5 | (x => x + 1)

但是以下操作无法编译:

  val r6 = 100! {x =>除非我写:

pre> val r6 = 100! {x:Int =>因此,如何避免需要键入函数?



我寻找类似问题的答案。一个解决方案是对函数进行curry。但是在这种情况下,我认为问题是类型流
从类Pip [A]的类型A到B当A =:= Try [B]。



欣赏任何指针。



TIA。

解决方案

匿名函数的参数类型是在具有预期类型的​​上下文中使用的,并且此预期类型是函数类型(或从Scala 2.12开始,SAM类型)。重载方法的参数没有预期的类型,因为它的类型需要知道选择的重载首先。因此,您需要为两个!> 方法指定不同的名称。


I have the following code:

class Pipe[ A ]( a: A ) {
  def |>[ B ]( f: A => B ) = f( a )
  def !>[ B ]( f: A => B ) : Try[B] = Try(f( a ))
  def !>[ B, C ]( f: B => C )(implicit ev: A =:= Try[B]) : Try[C] = a.map(f)
}

(Implicit and apply not included)

I am having problems with the "missing parameter type" error.The following code compiles correctly:

val r1 = 5 |> (x => x + 1)

However the following fails to compile:

val r6 = 100 !> { x  => x * 2 }

Unless I write:

val r6 = 100 !> { x  : Int => x * 2 }

So how do I get around the need to type the function?

I looked for answers on similar problems. One solution is to curry the function. However in this case I think the problem is type flowingfrom type A of class Pip[A] to B when A =:= Try[B].

Appreciate any pointers.

TIA.

解决方案

The only case in which you can omit an anonymous function's parameter type is when it is used in a context with an expected type, and this expected type is a function type (or, starting with Scala 2.12, a SAM type). Parameter for an overloaded method doesn't have an expected type, because its type needs to be known to choose the overload in the first place. So you need to give different names to the two !> methods.

这篇关于Scala中缺少类型运算符的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:50