Skip to content

Commit 9f6da05

Browse files
committed
Override toString for Lazy.
1 parent 476dc40 commit 9f6da05

File tree

2 files changed

+47
-6
lines changed

2 files changed

+47
-6
lines changed

src/main/java/io/github/nstdio/http/ext/Lazy.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,11 @@ public T get() {
3838

3939
return value;
4040
}
41+
42+
@Override
43+
public String toString() {
44+
return "Lazy{" +
45+
"value=" + (value != null ? value : "<not computed>") +
46+
'}';
47+
}
4148
}

src/test/kotlin/io/github/nstdio/http/ext/LazyTest.kt

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,7 @@ internal class LazyTest {
2828
@Test
2929
fun `Should invoke delegate once`() {
3030
//given
31-
val i = LongAdder()
32-
val delegate = Supplier<Int> {
33-
i.increment()
34-
1
35-
}
31+
val delegate = CountingSupplier(1)
3632
val lazy = Lazy(delegate)
3733

3834
//when
@@ -45,6 +41,44 @@ internal class LazyTest {
4541
}
4642

4743
//then
48-
i.toInt() shouldBe 1
44+
delegate.count() shouldBe 1L
45+
}
46+
47+
@Test
48+
fun `Should not resolve value when toString() called`() {
49+
//given
50+
val delegate = CountingSupplier(1)
51+
val lazy = Lazy(delegate)
52+
53+
//when
54+
val actual = lazy.toString()
55+
56+
//then
57+
actual.shouldBe("Lazy{value=<not computed>}")
58+
delegate.count() shouldBe 0L
59+
}
60+
61+
@Test
62+
fun `Should have proper toString`() {
63+
//given
64+
val lazy = Lazy { 10 }
65+
66+
//when
67+
lazy.get()
68+
val actual = lazy.toString()
69+
70+
//then
71+
actual.shouldBe("Lazy{value=10}")
72+
}
73+
74+
class CountingSupplier<T>(private val value: T) : Supplier<T> {
75+
private val count = LongAdder()
76+
77+
override fun get(): T {
78+
count.increment()
79+
return value
80+
}
81+
82+
fun count() = count.toLong()
4983
}
5084
}

0 commit comments

Comments
 (0)