Hello. I have a code like: ```"one ".trim() "two "...
# announcements
v
Hello. I have a code like:
Copy code
"one ".trim()
"two ".trim()
"three ".trim()
I would like to improve it with use of scope functions like
run
,
with
, etc. Can I do with them something like this:
Copy code
<scope_function> {
  "one ",
  "two ",
  "three ".
}.trim()
?
l
I'm not sure that this exactly is possible with a scope function
You want to reduce the calls to
trim
, but they're being used on different objects
s
listOf + map is relatively close to your pseudocode
l
scoping functions are useful when we want to to a lot of operations on one object and want to specify how we scope it
You might want to go
Copy code
listOf("one ", "two ", "three ").map { it.trim() }
As @SiebelsTim said
🙂 2
v
And in this case if for some reason it fails on a second object, will it continue further or it will exit?
s
Fail meaning it throws an exception? It will not continue.
v
Yes, throwing an exception in the middle of the list
l
For you to continue you would have to handle the exception
Copy code
listOf(...).map { try {it.trim()} catch(e: Exception) { .. }}
v
Though…. in my real case, if it fails in the middle and exits, then it’s fine, I think.
l
but by exiting we mean that it will throw an exception
v
Yes, I understand that. It’s fine to throw an exception. It’s even a desired behaviour
Thanks @LeoColman & @SiebelsTim
🙂 1
w
You could use an Extension on Collections:
Copy code
private fun Collection<String>.trim(): Collection<String> = map(String::trim)

    @Test
    fun asas1() {
        val result = listOf(
            "one ",
            "two ",
            "three "
        ).trim()
        val expectedResult = listOf(
            "one",
            "two",
            "three"
        )
        assertEquals(expectedResult, result)
    }

    @Test
    fun asas2() {
        val result = setOf(
            "one ",
            "two ",
            "three "
        ).trim()
        val expectedResult = listOf(
            "one",
            "two",
            "three"
        )
        assertEquals(expectedResult, result)
    }
l
And then you could use a extension function
Copy code
fun Collection<String>.trim() = this.map { it.trim() }
💯 3
v
Yes, also a good solution!
d
Wow, I suppose the test case is appreciated, I hope some assumptions can be made sometimes though 😅👌