2
votes

I am trying to create an array of Char using another array of Int's size. Code doesn't compile:

object Main {      
  def main(args: Array[String]): Unit = {        
    val mapping = Map(1 -> "ABC", 2 -> "DEF")    
    val a = mapping.keySet.toArray    
    val c = Array[Char](a.length)
  }   
}

The compiler throws an error: "type mismatch; found : Int required: Char"

when I change the code above to:

val c = Array[Char](2) // no compiler error

Looks like the compiler is interpreting my input not as a size param but instead thinking it's a Char such as an initial element of the Char array

Since in java this code would compile without a problem I was wondering what's the proper way of using another array length as a size param to init a different array in Scala?

2

2 Answers

5
votes

You should be using .ofDim in your last line

val c = Array.ofDim[Char](a.length)

The second one works

val c = Array[Char](2)

as the compiler is treating 2 itself as a character.

3
votes

Array type in scala has one confusing aspect, let me help you clarify it:

1.Array type has a class and a object, the object is called companion object for the specific class.

2.object Array has an apply method which in the code you use, but it can not be construct the same as the companion class.

To this snippet of code, the solution is:

object Main {      
  def main(args: Array[String]): Unit = {        
    val mapping = Map(1 -> "ABC", 2 -> "DEF")    
    val a = mapping.keySet.toArray    
    val c = new Array[Char](a.length)
  }   
}

Please be careful about the change of it, add new keyword to the created Array class.