Created
January 25, 2020 15:18
-
-
Save gonaumov/567f756fba95ad6b30bbab575b2f2fba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* You can edit, run, and share this code. | |
* play.kotlinlang.org | |
*/ | |
data class MyResponse( | |
val bigger: Int, | |
val lower: Int | |
) | |
fun main() { | |
val words = listOf("a", "abc", "ab", "def", "abcd") | |
val byLength = words.groupBy { when { | |
it.length > 2 -> "bigger" | |
else -> "lower" | |
} }.let { group -> | |
MyResponse( | |
bigger = group?.get("bigger").let { | |
it?.size ?: 0 | |
}, | |
lower = group?.get("lower").let { | |
it?.size ?: 0 | |
} | |
) | |
} | |
println(byLength.toString()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The real code is a bit different. I want to group some "record-set" and to"map" it to data object.
Link to Kotlin playground where you can test it:
https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS4zLjYxIiwiY29kZSI6Ii8qKlxuICogWW91IGNhbiBlZGl0LCBydW4sIGFuZCBzaGFyZSB0aGlzIGNvZGUuIFxuICogcGxheS5rb3RsaW5sYW5nLm9yZyBcbiAqL1xuZGF0YSBjbGFzcyBNeVJlc3BvbnNlKFxuICAgICAgICB2YWwgYmlnZ2VyOiBJbnQsXG4gICAgICAgIHZhbCBsb3dlcjogSW50XG4pXG5cbmZ1biBtYWluKCkge1xuICAgdmFsIHdvcmRzID0gbGlzdE9mKFwiYVwiLCBcImFiY1wiLCBcImFiXCIsIFwiZGVmXCIsIFwiYWJjZFwiKVxuICAgdmFsIGJ5TGVuZ3RoID0gd29yZHMuZ3JvdXBCeSB7IHdoZW4ge1xuICAgICAgIGl0Lmxlbmd0aCA+IDIgLT4gXCJiaWdnZXJcIlxuICAgICAgIGVsc2UgLT4gXCJsb3dlclwiXG4gICB9IH0ubGV0IHsgZ3JvdXAgLT5cbiAgICAgICBNeVJlc3BvbnNlKFxuICAgICAgICAgICBiaWdnZXIgPSBncm91cD8uZ2V0KFwiYmlnZ2VyXCIpLmxldCB7XG4gICAgICAgICAgICAgIGl0Py5zaXplID86IDAgXG4gICAgICAgICAgIH0sXG4gICAgICAgICAgIGxvd2VyID0gZ3JvdXA/LmdldChcImxvd2VyXCIpLmxldCB7XG4gICAgICAgICAgICAgIGl0Py5zaXplID86IDAgXG4gICAgICAgICAgIH1cbiAgICAgICApXG4gICAgICBcbiAgIH1cbiAgIHByaW50bG4oYnlMZW5ndGgudG9TdHJpbmcoKSlcbn0iLCJwbGF0Zm9ybSI6ImphdmEiLCJhcmdzIjoiIn0=