Assigning scala empty array
質問
I'm totally new to Scala. Here I have tried to assign a empty array to a variable, it was successful. But when I tried to append an integer element to the variable an error occured as below:
var c=Array()
c: Array[Nothing] = Array()
scala> c=Array(1)
<console>:8: error: type mismatch;
found : Int(1)
required: Nothing
c=Array(1)
^
What is the reason for this?
解決
When you do var c = Array()
, Scala computes the type as Array[Nothing]
and therefore you can't reassign it with a Array[Int]
. What you can do is:
var c : Array[Any] = Array()
c = Array(1)
or
var c : Array[Int] = Array()
c = Array(1)
他のヒント
Nothing
is the bottom type of Scala type hierarchy. It is a subtype of EVERY other type. See the documentation.
If you are not deciding which type of value you want to add to the empty Array, then you declare:
var c : Array[Any] = Array()
c = Array(1)
If you are deciding the data type, then you declare as:
var c : Array[Int] = Array()
c = Array(1)
所属していません StackOverflow