0
Kotlin: How can I print only string elements from this list !?
My code : fun main(){ var myList = {"ABC", 42, 100.0, "xyz", "123"} // Now what should I do to print String elements !? } I tried with lambda function, but couldn't find a way.
3 Réponses
0
Gotcha, I just only need to add this :
myList.filterIsInstance<String>().forEach{
Println (it)
}
+ 4
First of all u need to to use listOf() function, to create the list u want to create in ur question, and then u can easily use filter and forEach method to do this thing, see:
val myList = listOf("ABC", 42, ...)
// this will make List of type of class Any
// Now im checking if the element is String or not, and then printing it
myList.filter{ it is String }.forEach{
println(it)
}
Hope this helps u.
Keep coding in kotlin!!☺👍
+ 3
You could do this as well.
for(element in myList){
if(element is String){
println(element);
}
}