【问题标题】:Can I create a tuple from a non-comma separated set of tokens in Scala?我可以在 Scala 中从一组非逗号分隔的标记中创建一个元组吗?
【发布时间】:2011-06-10 19:49:57
【问题描述】:

我正在继续我的 Stack-Overflow-Driven 测试 DSL 编程 - 感谢所有迄今为止做出贡献的人!

目前我的 DSL 是这样的

scenario("Incorrect password") {
  given("user visits", the[AdminHomePage])
  then(the[SignInPage], "is displayed")      

  when("username", "admin", "and password", "wrongpassword", "are entered")
  then(the[SignInPage], "is displayed")      
  and("Error message is", "Sign in failed")
}

给定,when 和 then 是采用 Any 的方法,因此当像这样调用它们时,它们会传递一个参数元组 - Why and how is Scala treating a tuple specially when calling a one arg function?

理想情况下,我会去掉逗号,这样读起来会更好,只有空格分隔标记

scenario("Incorrect password") {
  given("user visits" the[AdminHomePage])
  then(the[SignInPage] "is displayed")      

  when("username" "admin" "and password" "wrongpassword" "are entered")
  then(the[SignInPage] "is displayed")      
  and("Error message is" "Sign in failed")
}

谁能想到任何可以让我实现这个目标的技术,还是对于内部 DSL 来说太过分了?

【问题讨论】:

    标签: scala dsl


    【解决方案1】:

    您需要在“令牌”之间使用方法/运算符。对于pairs,已经有->,例如

    println("hello" -> 12 -> '!' -> 12.0)
    //--> (((hello,12),!),12.0)
    

    【讨论】:

    • 我确实考虑过使用 |或类似的东西,但一切似乎都不像逗号那么突兀,需要做更多的工作。
    • 通常“is”在您的情况下似乎效果很好:then(the[SignInPage] is "displayed"), and("ErrorMessage" is "Sign in failed")
    【解决方案2】:

    不,您不能从空格分隔的标记创建元组(尽管您可以使用自定义运算符作为分隔符而不是逗号)。你可以做的是像这样使用无点语法:

    obj method obj method obj ...
    

    许多 DSL 实现(如规范)利用这种语法来创建更多“类似文本”的语法。

    【讨论】:

    • 我想知道这是否是一条路径,但其他所有标记都必须是方法的名称?
    • 可以,所以可以给String类型加上“扩展方法”,但是方法名本身不能是字符串,例如:"hello" is "displayed" and "groovy"
    【解决方案3】:

    不确定它是否有效:

    如前所述,您可以使用运算符表示法调用一个参数方法。还有一个 Dynamic Trait 允许动态调用方法:http://www.scala-lang.org/api/current/index.html#scala.Dynamic

    因此,如果您从实现动态特征的对象开始,它可能会起作用..

    【讨论】:

    • 但是我仍然需要所有其他标记都可以解释为方法名称...?
    • 它会被解释为一个方法名,但该方法不需要存在。
    • 确实,但这意味着没有空格,不能只使用字符串等
    猜你喜欢
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2014-03-09
    • 2022-10-05
    • 2011-02-10
    • 2017-04-02
    相关资源
    最近更新 更多