2

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 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.