Java Stream with :: new to Kotlin
I am trying to convert the following Spring security code from Java to Kotlin.
Java:
Collection<? extends GrantedAuthority> authorities =
Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
Kotlin:
val authorities = Arrays.stream(claims[AUTHORITIES_KEY].toString().split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray())
.map(SimpleGrantedAuthority())
.collect(Collectors.toList<SimpleGrantedAuthority>())
I am getting a type mismatch error ( Required:
Function<in String!, out (???..???)>!
) on .map(SimpleGrantedAuthority())
. How do I convert the above Java code to Kotlin with the keyword ::new
correctly?
source to share
Usage Arrays.stream
does not make the code overly readable:
val authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",").toTypedArray())
.map(::SimpleGrantedAuthority).collect(Collectors.toList<SimpleGrantedAuthority>())
However, in Kotlin, you can do better:
val authorities = claims.get(AUTHORITIES_KEY).toString()
.split(",").filterNot { it.isEmpty() }
.map(::SimpleGrantedAuthority)
source to share
You need to pass the lambda expression to the body map
. You created a new instance SimpleGrantedAuthority
instead of creating a function that returns a new instance SimpleGrantedAuthority
.
It's a subtle difference.
To fix your problems, you can use the constructor link:
.map(::SimpleGrantedAuthority)
or define the lambda expression manually:
.map({ SimpleGrantedAuthority() })
Also, instead of:
claims.get(AUTHORITIES_KEY)
You can do:
claims[AUTHORITIES_KEY]
You don't really need to use the Stream API in Kotlin. The Native Collections API is powerful enough:
val auths = claims[AUTHORITIES_KEY].toString()
.split(",")
.filterNot(String::isEmpty)
.map(::SimpleGrantedAuthority)
source to share