8000 exceptions-to-values.7 : flatMap errors · java-to-kotlin/code@442f413 · GitHub
[go: up one dir, main page]

Skip to content

Commit 442f413

Browse files
Duncan McGregordmcg
authored andcommitted
exceptions-to-values.7 : flatMap errors
1 parent 15cf851 commit 442f413

File tree

1 file changed

+24
-19
lines changed

1 file changed

+24
-19
lines changed

src/main/java/travelator/marketing/HighValueCustomersReport.kt

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
package travelator.marketing
22

3-
import com.natpryce.Failure
4-
import com.natpryce.Result
5-
import com.natpryce.Success
6-
import com.natpryce.recover
3+
import com.natpryce.*
74

85
fun Sequence<String>.toHighValueCustomerReport(
96
onErrorLine: (ParseFailure) -> Unit = {}
@@ -34,21 +31,29 @@ private fun Sequence<String>.withoutHeader() = drop(1)
3431

3532
internal fun String.toCustomerData(): Result<CustomerData, ParseFailure> =
3633
split("\t").let { parts ->
37-
if (parts.size < 4)
38-
return Failure(NotEnoughFieldsFailure(this))
39-
val score = parts[3].toIntOrNull() ?:
40-
return Failure(ScoreIsNotAnIntFailure(this))
41-
val spend = if (parts.size == 4) 0.0 else parts[4].toDoubleOrNull() ?:
42-
return Failure(SpendIsNotADoubleFailure(this))
43-
Success(
44-
CustomerData(
45-
id = parts[0],
46-
givenName = parts[1],
47-
familyName = parts[2],
48-
score = score,
49-
spend = spend
50-
)
51-
)
34+
parts
35+
.takeUnless { it.size < 4 }
36+
.asResultOr { NotEnoughFieldsFailure(this) }
37+
.flatMap { parts ->
38+
parts[3].toIntOrNull()
39+
.asResultOr { ScoreIsNotAnIntFailure(this) }
40+
.flatMap { score: Int ->
41+
(if (parts.size == 4) 0.0
42+
else parts[4].toDoubleOrNull())
43+
.asResultOr { SpendIsNotADoubleFailure(this) }
44+
.flatMap { spend ->
45+
Success(
46+
CustomerData(
47+
id = parts[0],
48+
givenName = parts[1],
49+
familyName = parts[2],
50+
score = score,
51+
spend = spend
52+
)
53+
)
54+
}
55+
}
56+
}
5257
}
5358

5459
sealed class ParseFailure(open val line: String)

0 commit comments

Comments
 (0)
0