Scala: short expression for expressing the following construct

I will give the C-style “parentheses” pseudocode to show what I would like to express differently:

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, this is not a question of my question: I would like to know how I could rewrite what is inside the loop using Scala.

My goal is not to have the shortest code: this is because I would like to understand what manipulations can be done on method names (?) In Scala.

Can you do something like the following in Scala (the next 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 would like to know if the test result (i == 3 || i == 5 || i == 982) can be used to send between two methods or to add a "not" to the expression.

I do not know if this makes sense, please be kind (see my profile) :)

+4
source share
4 answers

While the solution of the pelotome is much better for this case, you can also do this (which is a bit closer to what you asked initially):

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

The construction of names can be dynamically done using reflection, but this, of course, will not be brief.

+10
source
 assertTrue(isCromulent(i) == (i==3||i==5||i==982)) 
+8
source

On a system like Scala, it is not possible to dynamically create a method name based on a condition.

But in this case it is not necessary at all.

 val condition = i == 3 || i == 5 || i == 982 assertEquals(condition, isCromulent(i)) 
+6
source

I hope no one removes this answer, but rather an answer than a direct answer.

I found the question and answers so far very interesting and spent some time looking for a template-based alternative.

The following is an attempt to summarize this (very specific) category of testing:

 class MatchSet(s: Set[Int]) {def unapply(i: Int) = s.contains(i)} object MatchSet {def apply(s: Int*) = new MatchSet(Set(s:_*))} val cromulentSet = MatchSet(3, 5, 982) 0 until n foreach { case i @ cromulentSet() => assertTrue(isCromulent(i)) case i => assertFalse(isCromulent(i)) } 

The idea is to create ranges of values ​​contained in MatchSet instances, instead of using explicit matches.

+2
source

Source: https://habr.com/ru/post/1316503/


All Articles