Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion core/src/main/scala/ox/util.scala
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,24 @@ extension [T](inline t: T)
try f(e)
catch case ee: Throwable => e.addSuppressed(ee)
throw e

/** Print the value of this expression, preceeded with the given label, and return the original value.
*
* @example
* {{{
* import ox.debug
* val x = 20
* x.debug("current value of x")
*
* // prints: current value of x: 20
* }}}
*
* @see
* [[debug]] as a top-level method for printing the code corresponding to an expression, alongside its value.
*/
inline def debug(label: String): T =
println(s"$label: $t")
t
end extension

extension [T](inline f: Future[T])
Expand Down Expand Up @@ -115,7 +133,9 @@ inline def timed[T](operation: => T): (FiniteDuration, T) =
val duration = (after - before).nanos
(duration, result)

/** Prints the code and result of the expression to the standard output. Equivalent to `println(xAsCode + " = " + x)`.
/** Prints the code and the value of the expression to the standard output. Equivalent to `println(xAsCode + " = " + x)`.
* @see
* [[debug]] as an extension method on a value.
*
* @example
* {{{
Expand Down
22 changes: 21 additions & 1 deletion doc/utils/utility.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Top-level methods:
* `sleep(scala.concurrent.Duration)` blocks the current thread/fork for the given duration; same as `Thread.sleep`, but
using's Scala's `Duration`
* `debug(expression)` prints the code representing the expression, and the value of the expression to standard output,
using `println`
using `println`.

Extension functions on arbitrary expressions:

Expand All @@ -21,9 +21,29 @@ Extension functions on arbitrary expressions:
operations
* `.tapException(Throwable => Unit)` and `.tapNonFatalException(Throwable => Unit)` allow running the provided
side-effecting callback when the expression throws an exception
* `.debug(label)` prints the value preceeded with the given label, and returns the original value

Extension functions on `scala.concurrent.Future[T]`:

* `.get(): T` blocks the current thread/fork until the future completes; returns the successful value of the future, or
throws the exception, with which it failed

## Examples

Debug utilities:

```scala mdoc
import ox.*

val x = 20
val y = 10
debug(x * 2 + y)
```

```scala mdoc
import ox.*

def transform(n: Int): Long = n * n * n

transform(5).debug("transformation result")
```