blue-sky
blue-sky

Reputation: 53876

Why does it should "" {} type check in scalatest?

How does it should accept a String and then a function without parenthesis :

import org.scalatest.FlatSpec
import scala.collection.mutable.Stack

class StackSpec extends FlatSpec {

  it should "pop values in last-in-first-out order" in {

  }

}

why should it not be :

it(should("pop values in last-in-first-out order" in {

  }))

Closest I came to allowing similar to compile is :

object st {

  class fs {

    def it(f: => Unit) = {

    }

    def should(s: String)(f: => Unit): Unit = {
      Unit
    }

    it(should("pop values in last-in-first-out order") {

    })

  }

}

Upvotes: 1

Views: 111

Answers (2)

mattinbits
mattinbits

Reputation: 10428

The . to call functions of objects and the () around the parameters of functions are optional in scala. So the trick is the return objects in a chain which implement functions providing the api you want. Simple example:

object InObj {

  def in(func : => Unit) = func
}

object ShouldObj {

  def should(x: String) = InObj
}

trait It {

  def it = ShouldObj
}

class MyClass extends It {

  val f = it should "Do something" in {

  }
}

Upvotes: 4

dth
dth

Reputation: 2337

Scala has certain rules how operators and infix method names are converted into method calls.

it should "foo" in {}

is converted into

it.should("foo").in({})

In the case where you do not use "it" but some String a implicit conversion from String to some wrapper helps to provide the should-method.

Upvotes: 2

Related Questions