是否可以在 lambda 表达式中检索字符串?
Is it possible to retrieve the string within the lambda expression?
使用 String Spec 编写测试:
class stl : StringSpec() {
init {
"triangle.stl" {
...
}
}
}
是否可以在 lambda 表达式中检索 "triangle.stl"
?
您必须自己存储对字符串的引用。像
class stl : StringSpec() {
init {
val spek = "triangle.stl"
spek {
// use spek in here
}
}
}
看起来 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
}
}
使用 String Spec 编写测试:
class stl : StringSpec() {
init {
"triangle.stl" {
...
}
}
}
是否可以在 lambda 表达式中检索 "triangle.stl"
?
您必须自己存储对字符串的引用。像
class stl : StringSpec() {
init {
val spek = "triangle.stl"
spek {
// use spek in here
}
}
}
看起来 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
}
}