Fred
Fred

Reputation: 579

Scala array with no name

Here is how I can check if a number is even/odd in Ruby:

def even_or_odd(number)
  ['Even', 'Odd'][number % 2]
end

The closest I have in Scala is the following:

  def evenOrOdd(number: Int): String = {
     val a = Array("Even", "Odd")
     a(number % 2)
  }

What I really want to do is something like this, but it won't compile:

  def evenOrOdd(number: Int): String = {
    ("Even", "Odd")(number % 2)
  }

Firstly, what is this type of 'anonymous' structure called? Secondly, what is an elegant way to use it? If you have a similar example that illustrates the power/conciseness/clarity of Scala, I'd like to see it.

Upvotes: 0

Views: 111

Answers (3)

Dominic Egger
Dominic Egger

Reputation: 1016

("Even", "Odd") is of type (String,String) which is an alias for Tuple2[String, String] it's accessors are ._1 and ._2

you could do Array("Even", "Odd")(number % 2) or EDIT: as pointed out in the comments this won't actually work. This will though Array("Even", "Odd").apply(number % 2)

number % 2 match {
    case 0 => "Even"
    case 1 => "Odd"
    case -1 => "Odd" //EDIT: as per comment. I forgot about this case
}

Upvotes: 3

Bogdan Vakulenko
Bogdan Vakulenko

Reputation: 3390

def evenOrOdd(number: Int) = 
 List("Even","Odd")(number % 2)

Upvotes: 2

ygor
ygor

Reputation: 1756

This compiles:

def evenOrOdd(number: Int): String = {
    Array("Even", "Odd").apply(number % 2)
}

In most cases, calling the apply method can be omitted, because it comes with its syntactic sugar. However, in this case, it does not work. You either have to extract the Array("Even", "Odd") into a var, var or def or you have to give up on the syntactic sugar.

The reason, why the syntactic sugar Array("Even", "Odd")(number % 2) does not work, is somehow hard to explain, but it is caused by following:

  • Java does not allow generic array creation (e.g. new T[], where T is a generic type)
  • Scala allows generic array creation by utilizing ClassTag in Array.apply; the ClassTag comes with its own syntactic sugar, which makes Array("Even", "Odd")(number % 2) invalid

Upvotes: 2

Related Questions