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

Scalatest Scalamock在以两种方式声明同一函数时表现不同,scala,scalatest,scalamock,Scala,Scalatest,Scalamock,如果我有一个Scala trait,上面定义了两个函数,一个是使用签名def foo:Int=>String定义的,另一个是使用参数和返回类型def bar(myInt:Int):String声明的,那么这些方法的行为就不同了 import org.scalamock.scalatest.MockFactory import org.scalatest.{Matchers, WordSpec} class DefTest { trait DefTrait { def foo :

如果我有一个Scala trait,上面定义了两个函数,一个是使用签名
def foo:Int=>String
定义的,另一个是使用参数和返回类型
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说,当和
预期值:functionaldapter0[Boolean],实际值:MatchAny
时,方法的参数太多

SBT表示:

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

  • 这两种类型的函数声明之间有什么区别?我认为它们是等价的,到目前为止,我似乎能够互换使用它们
  • 当42返回“yay”语法时,是否可以将签名函数定义
    foo:Int=>String
    defStub.foo>一起使用

  • 1。这两种类型的函数声明之间有什么区别?

    对于
    def foo:Int=>String
    它返回一个不带accept参数的高阶函数:

    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.当42返回“yay”语法时,是否可以将签名函数定义foo:Int=>字符串与defStub.foo一起使用?

    对于
    def foo:Int=>String
    它不接受参数,因此应该使用
    when()
    进行此操作,它的返回类型是
    Int=>String
    ,因此对于此方法,应该
    返回一个
    高阶函数。比如:

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

    1。这两种类型的函数声明之间有什么区别?

    对于
    def foo:Int=>String
    它返回一个不带accept参数的高阶函数:

    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.当42返回“yay”语法时,是否可以将签名函数定义foo:Int=>字符串与defStub.foo一起使用?

    对于
    def foo:Int=>String
    它不接受参数,因此应该使用
    when()
    进行此操作,它的返回类型是
    Int=>String
    ,因此对于此方法,应该
    返回一个
    高阶函数。比如:

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