【问题标题】:Scalatest Scalamock behaves differently with same function declared two waysScalatest Scalamock 以两种方式声明的相同函数的行为不同
【发布时间】:2017-06-28 16:12:04
【问题描述】:

如果我有一个 Scala 特征,其中定义了两个函数,一个仅使用签名 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 说有 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" 语法一起使用?

【问题讨论】:

    标签: scala scalatest scalamock


    【解决方案1】:

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

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

    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.是否可以使用签名函数定义 foo: Int => String 和 defStub.foo _ when 42 return "yay" 语法?

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

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

    【讨论】:

      猜你喜欢
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多