Scalatest Scalamock 以两种方式声明相同的函数时表现不同

Scalatest Scalamock behaves differently with same function declared two ways

如果我有一个 Scala 特征,上面定义了两个函数,一个仅使用签名 def foo : Int => String 定义,另一个函数使用参数和 return 类型 def bar(myInt : Int): String 声明然后我得到这些方法的不同行为。

import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, WordSpec}

class DefTest {

  trait DefTrait {
    def foo : Int => String
    def bar(myInt: Int) : String
  }

  class DefTest extends WordSpec with Matchers with MockFactory {
    val defStub = stub[DefTrait]

    defStub.bar _ when * returns "Works"
    defStub.foo _ when * return "nope"

  }
}

IntellJ 说有 Too many arguments for method whenexpected: FunctionAdapter0[Boolean], actual: MatchAny

SBT 说:

type mismatch;
[error]  found   : org.scalamock.matchers.MatchAny
[error]  required: org.scalamock.function.FunctionAdapter0[Boolean]
[error]     defStub.foo _ when * returns "nope"
[error]                        ^

这让我想知道:

  1. 这两种函数声明有什么区别?我认为它们是等价的,到目前为止我似乎可以互换使用它们。
  2. 是否可以将签名函数定义 foo: Int => StringdefStub.foo _ when 42 return "yay" 语法一起使用?

1.这两种函数声明有什么区别?

对于 def foo : Int => String 它是 return 一个没有接受参数的 高阶 函数:

scala> :kind -v foo
scala.Function1's kind is F[-A1,+A2]
* -(-)-> * -(+)-> *
This is a type constructor: a 1st-order-kinded type.

而当你调用foo(2)时,等于foo.apply(2)apply方法用于函数执行。

对于 def bar(myInt: Int) : String,它是一种接受 Int 参数的方法。

2.是否可以使用带有 defStub.foo _ when 42 return "yay" 语法的签名函数定义 foo: Int => String?

对于def foo : Int => String它不接受参数,所以你应该为此使用when(),它的return类型是Int => String,所以你应该returns 此方法的 高阶函数 。喜欢:

defStub.foo _ when() returns((i: Int) => "nope")