gpt4 book ai didi

scala - 函数返回的 Gatling exec 函数

转载 作者:行者123 更新时间:2023-12-04 17:55:14 24 4
gpt4 key购买 nike

我正在使用 Scala IDE (Eclipse Luna) 处理 Gatling,我遇到了这个问题,我想了解一下。

我有这个功能

import io.gatling.core.session.Session
import io.gatling.core.Predef._

object Predef {
def justDoIt(param: String): Session => Session = s => s.set("some", param)
}

我正尝试以这种方式使用它

val testScenario1 = scenario("Test")
.exec(justDoIt("hello world"))

val testScenario2 = scenario("Test")
.exec(justDoIt("hello world")(_))

出于某种原因,只有后者可以编译。前者提示重载不适用于 Session => Session 类型的参数。

我想了解这两行之间的区别以及为什么第一行编译失败。

我还做了以下测试,两种语法似乎都在做同样的事情:

scala> def hello(fn: String => String) = fn("Hello")
hello: (fn: String => String)String

scala> def message(name: String): String => String = greeting => s"$greeting $name"
message: (name: String)String => String

scala> hello(message("world"))
res1: String = Hello world

scala> hello(message("world")(_))
res2: String = Hello world

最佳答案

根据做docs :

exec can also be passed an Expression function.

... 这是 alias for :

Session => Validation[T]

另请注意第一个链接的摘录:

For those who wonder how the plumbing works and how you can return a Session instead of Validation[Session] in the above examples, that’s thanks to an implicit conversion.

现在,有了这些信息,您可以看到在第一种情况下,您传递给 exec 的是 Session => Session 类型的东西(没有隐式转换到 Expression[Session] 存在于范围内),你会得到编译错误。

在第二种情况下,您将占位符/部分应用程序用于:

justDoIt("hello world")(_)

...相当于:

x => justDoIt("hello world")(x)

... 可以受益于返回值的隐式转换(从 SessionValidation[Session]),结果整个表达式被推断为符合 Expression[Session] 这正是 exec 所要求的。

更新:这里是 relevant implicit进行转换。

更新 2: 要使您的原始示例正常工作,您可以像这样简单地更改 justDoIt 的返回类型(以从隐式转换中获益):

def justDoIt(param: String): Session => Validation[Session] = s => s.set("some", param)

关于scala - 函数返回的 Gatling exec 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45626020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com