Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala check if element is present in a list

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!

like image 933
Dario Oddenino Avatar asked Jan 10 '13 21:01

Dario Oddenino


People also ask

How do you check if a value is present in a list in Scala?

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 .

How do you check if a string contains a substring in Scala?

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.

How do I append to a list in Scala?

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”.

How do you define a list in Scala?

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.


1 Answers

Just use contains

myFunction(strings.contains(myString)) 
like image 91
Kim Stebel Avatar answered Sep 23 '22 12:09

Kim Stebel