Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: concise way to express the following construct

Tags:

scala

I'll give some C-style "bracket" pseudo-code to show what I'd like to express in another way:

for (int i = 0; i < n; i++) {
    if (i == 3 || i == 5 || i == 982) {
        assertTrue( isCromulent(i) );      
    } else {
        assertFalse( isCromulent(i) );
    }
}

The for loop is not very important, that is not the point of my question: I'd like to know how I could rewrite what is inside the loop using Scala.

My goal is not to have the shortest code possible: it's because I'd like to understand what kind of manipulation can be done on method names (?) in Scala.

Can you do something like the following in Scala (following is still some kind of pseudo-code, not Scala code):

assert((i==3 || i==5 || i==982)?True:False)(isCromulent(i))

Or even something like this:

assertTrue( ((i==3 || i==5 || i==982) ?  : ! ) isCromulent(i) )

Basically I'd like to know if the result of the test (i==3 || i==5 || i==982) can be used to dispatch between two methods or to add a "not" before an expression.

I don't know if it makes sense so please be kind (look my profile) :)

like image 343
NoozNooz42 Avatar asked Nov 28 '22 23:11

NoozNooz42


1 Answers

While pelotom's solution is much better for this case, you can also do this (which is a bit closer to what you asked originally):

(if (i==3||i==5||i==982) assertTrue else assertFalse)(isCromulent(i))

Constructing names dynamically can be done via reflection, but this certainly won't be concise.

like image 152
Alexey Romanov Avatar answered Dec 16 '22 07:12

Alexey Romanov