简体   繁体   English

Scala - 如何在多行字符串文字中使用变量

[英]Scala - how to use variables in a multi-line string literal

I want to call value of ' myActionID ' variable.我想调用“ myActionID ”变量的值。 How do I do that?我该怎么做? If i pass static value like "actionId":1368201 to myActionID then it works, but If I use "actionId" : ${actionIdd} it gives error.如果我将像 "actionId":1368201 这样的静态值传递给 myActionID 那么它就可以工作,但是如果我使用 "actionId" : ${actionIdd} 它会出错。

Here's the relevant code:这是相关的代码:

class LaunchWorkflow_Act extends Simulation {

    val scenarioRepeatCount = 1
    val userCount = 1
    val myActionID = "13682002351"
    
    val scn = scenario("LaunchMyFile")
        .repeat (scenarioRepeatCount) {
            exec(session => session.set("counter", (globalVar.getAndIncrement+" "+timeStamp.toString())))
            .exec(http("LaunchRequest")
            .post("""/api/test""")
            .headers(headers_0)
            .body(StringBody(
                """{    "actionId": ${myActionID} ,
                "jConfig": "{\"wflow\":[{\"Wflow\":{\"id\": \"13500145349\"},\"inherit-variables\": true,\"workflow-context-variable\": [{\"variable-name\": \"externalFilePath\",\"variable-value\": \"/var/nem/nem/media/mount/assets/Test.mp4\"},{\"variable-name\": \"Name\",\"variable-value\": \"${counter}\"}]}]}"
                }""")))

            .pause(pause) 

        }
    }

setUp(scn.inject(atOnceUsers(userCount))).protocols(httpProtocol)

Everything works fine If I put value 13682002351 instead of myActionID.如果我输入值 13682002351 而不是 myActionID,一切正常。 While executing this script in Gatling I am Getting this error在 Gatling 中执行此脚本时,出现此错误

ERROR ighttp.action.HttpRequestAction - 'httpRequest-3' failed to execute: No attribute named 'myActionID' is defined错误 ighttp.action.HttpRequestAction - 'httpRequest-3' 执行失败:未定义名为 'myActionID' 的属性

Scala has various mechanisms for String Interpolation (see docs ), which can be used to embed variables in strings. Scala 有各种字符串插值机制(参见文档),可用于在字符串中嵌入变量。 All of them can be used in conjunction with the triple quotes """ used to create multi-line strings.所有这些都可以与用于创建多行字符串的三重引号"""使用。

In this case, you can use:在这种情况下,您可以使用:

val counter = 12
val myActionID = "13682002351"
val str = s"""{    
                "actionId": $myActionID ,
                "jConfig": "{\"wflow\":[{\"Wflow\":{\"id\": \"13500145349\"},\"inherit-variables\": true,\"workflow-context-variable\": [{\"variable-name\": \"externalFilePath\",\"variable-value\": \"/var/nem/nem/media/mount/assets/Test.mp4\"},{\"variable-name\": \"Name\",\"variable-value\": \"${counter}\"}]}]}"
              }"""

Notice the s prepended to the string literal, and the dollar sign prepended to the variable names.注意字符串字面前的s和变量名前的美元符号。

Using S interpolated String we can do this easily:使用S 内插字符串,我们可以轻松做到这一点:

 s"""Hello Word , Welcome Back!
      How are you doing ${userName}"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM