scalatest“一个堆栈"应该“做某事"——卧槽?字符串的方法应该如何? [英] scalatest "A stack" should "do something" -- wtf? How is should a method of string?

查看:60
本文介绍了scalatest“一个堆栈"应该“做某事"——卧槽?字符串的方法应该如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 scala,我发现一些语法令人困惑.例如来自 scalatest 主页

I'm just starting out with scala here and I'm finding some of the syntax confusing. For example from the scalatest main page

  class ExampleSpec extends FlatSpec with Matchers {

    "A Stack" should "pop values in last-in-first-out order" in {...}
 }

正如我所读到的,这意味着应该"是字符串堆栈"的方法吗?如果这是对的,那是如何发生的?从 Scala 提示符下它似乎不起作用

As I read it that means "should" is a method of string "A stack"? If that is right, how does that happen? It doesn't seem to work from the scala prompt

 scala> class ExampleSpec {
 |    "A Stack" should "pop values"
 | }
 <console>:9: error: value should is not a member of String
      "A Stack" should "pop values"

如果应该"不是上面代码片段中字符串A Stack"的方法,那么我该如何正确读取代码片段?什么是应该",它与字符串有什么关系?有什么线索吗?

If "should" is not a method of string "A Stack" in the above snippet then how am I to read the snippet correctly? What is "should" and how does it relate to the string? Any clues?

推荐答案

这通常被称为 Pimp My Library 丰富我的库模式,我们可以在其中扩展其他库(在这种情况下是 Scala 字符串)使用我们自己的方法使用隐式转换.

This is commonly known as the Pimp My Library Enrich My Library pattern where we can extend other libraries (in this case Scala strings) with our own methods by using implicit conversions.

它的工作方式是 FlatSpec 混合了一个名为 ShouldVerb 的特性,它定义了以下隐式转换:

The way it works is that FlatSpec mixes in a trait called ShouldVerb which has the following implicit conversion defined:

 implicit def convertToStringShouldWrapper(o: String): StringShouldWrapperForVerb =
   new StringShouldWrapperForVerb {
     val leftSideString = o.trim
   }

并且 StringShouldWrapperForVerb 定义了 should 方法:

And StringShouldWrapperForVerb has the should method defined:

def should(right: String) ....

它在 REPL 中对你不起作用的原因是你没有 FlatSpec 并且通过它混合了 ShouldVerb 特性.

The reason it does not work in the REPL for you is that you don't have FlatSpec and via that the ShouldVerb trait mixed in.

您可以在文档下隐式类.

这篇关于scalatest“一个堆栈"应该“做某事"——卧槽?字符串的方法应该如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆