是否有可能检索lambda表达式中的字符串?

使用字符串规范编写测试:

class stl : StringSpec() { init { "triangle.stl" { ... } } } 

是否有可能检索lambda表达式中的"triangle.stl"

它看起来不像StringSpec公开这个信息,但是你可以扩展StringSpec这样做。 例如:

 class Spec : StringSpec() { init { "triangle.stl" { testCase -> println(testCase.name) } } operator fun String.invoke(test: (TestCase) -> Unit): TestCase { var tc: TestCase? = null tc = invoke(fun() { test(tc!!) }) return tc } } 

或者为避免函数与String.invoke冲突,可以用自己的语法来扩展它。 例如:

 class Spec : StringSpec() { init { "triangle.stl" testCase { println(name) } } infix fun String.testCase(test: TestCase.() -> Unit): TestCase { var tc: TestCase? = null tc = invoke { test(tc!!) } return tc } } 

你将不得不自己存储对字符串的引用。 就像是

 class stl : StringSpec() { init { val spek = "triangle.stl" spek { // use spek in here } } }