Is there a way to shorter this `listOf(1) + listOf...
# announcements
n
Is there a way to shorter this
listOf(1) + listOf(2,3,4,5)
. Something like this
1 :: listOf(2,3,4,5)
.
k
listOf(1,2,3,4,5)
🧌
👏 4
🙏 2
n
😑
k
If this is something you have to do often you can can define something like this:
Copy code
operator fun <T> T.plus(list: List<T>): List<T> =
    ArrayList<T>(list.size + 1).also { it.add(this); it.addAll(list) }
n
This means ‘no’. Ok.
k
Huh?
n
Yeah, your solution works fine. I mean it’s not built-in one. Though it may be JB’s strategy..
k
Ah I see. Actually the problem with my function is that it shadows
Iterable<T>.plus(Iterable<T>)
, so it can cause unexpected behavior.
n
Does it?
Iterable<T>.plus(List<Iterable<T>>)
would be shodawed.
Also body can be shorter:
operator fun <T> T.plus(list: List<T>): List<T> = list + this
k
That changes the other, and if you wanted that you could have done
listOf(2,3,4,5) + 1
in the first palce.
I'm not sure if it is shadowed actually, the compiler might pick
T = Any
and shadow it that way.
n
Oh.. you’re right 🙂