better elvis + throw

+added run {}
This commit is contained in:
Sergey Chernov 2025-08-18 00:56:52 +03:00
parent 835333dfad
commit 95c1da60ed
4 changed files with 42 additions and 0 deletions

View File

@ -225,6 +225,19 @@ It works much like `also`, but is executed in the context of the source object:
assertEquals(p, Point(2,3)) assertEquals(p, Point(2,3))
>>> void >>> void
## run
Executes a block after it returning the value passed by the block. for example, can be used with elvis operator:
var someVar = null
val result = someVar ?: run {
someVar = 121
"reset"
}
assertEquals("reset", result)
assertEquals(121, someVar)
>>> void
## Math ## Math
It is rather simple, like everywhere else: It is rather simple, like everywhere else:
@ -1311,6 +1324,7 @@ See [math functions](math.md). Other general purpose functions are:
| flow {} | create flow sequence, see [parallelism] | | flow {} | create flow sequence, see [parallelism] |
| delay, launch, yield | see [parallelism] | | delay, launch, yield | see [parallelism] |
| cached(builder) | remembers builder() on first invocation and return it then | | cached(builder) | remembers builder() on first invocation and return it then |
| let, also, apply, run | see above, flow controls |
# Built-in constants # Built-in constants

View File

@ -376,6 +376,11 @@ class Compiler(
} }
"throw" -> {
val s = parseThrowStatement()
operand = Accessor { s.execute(it).asReadonly }
}
else -> operand?.let { left -> else -> operand?.let { left ->
// selector: <lvalue>, '.' , <id> // selector: <lvalue>, '.' , <id>
// we replace operand with selector code, that // we replace operand with selector code, that

View File

@ -315,6 +315,9 @@ open class Obj {
args.firstAndOnly().callOn(copy(Arguments(thisObj))) args.firstAndOnly().callOn(copy(Arguments(thisObj)))
thisObj thisObj
} }
addFn("run") {
args.firstAndOnly().callOn(this)
}
addFn("getAt") { addFn("getAt") {
requireExactCount(1) requireExactCount(1)
thisObj.getAt(this, requiredArg<Obj>(0)) thisObj.getAt(this, requiredArg<Obj>(0))

View File

@ -2961,5 +2961,25 @@ class ScriptTest {
""".trimIndent()) """.trimIndent())
} }
@Test
fun testElvisAndThrow() = runTest {
eval("""
val x = assertThrows {
null ?: throw "test" + "x"
}
assertEquals( "testx", x.message)
""".trimIndent())
}
@Test
fun testElvisAndRunThrow() = runTest {
eval("""
val x = assertThrows {
null ?: run { throw "testx" }
}
assertEquals( "testx", x.message)
""".trimIndent())
}
} }