I need to check if a string is present in a list, and call a function which accepts a boolean accordingly.
Is it possible to achieve this with a one liner?
The code below is the best I could get:
val strings = List("a", "b", "c") val myString = "a" strings.find(x=>x == myString) match { case Some(_) => myFunction(true) case None => myFunction(false) }
I'm sure it's possible to do this with less coding, but I don't know how!
contains() function in Scala is used to check if a list contains the specific element sent as a parameter. list. contains() returns true if the list contains that element. Otherwise, it returns false .
Use the contains() Function to Find Substring in Scala Here, we used the contains() function to find the substring in a string. This function returns a Boolean value, either true or false.
This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.
Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With