Question: Convert the text string "[1, 2, 3, 4, 5]" to an array.
Answer:
val x = "[1, 2, 3, 4, 5]"
Val y =x Slice (1, x.length-1) replace (",", "") Split ("")
var y1= x Slice (1, x.length-1) replace (",", "") Split ("") Map (_.toint)
Y1:array[int] = Array (1, 2, 3, 4, 5)
or write
var y1= x.slice (1, x.length-1). Replace (",", ""). Split (""). Map (_.toint)
Or
Val y:array[int]= x Slice (1, x.length-1) replace (",", "") Split ("") Map (_.toint)
Scala encourages programmers to declare variables with Val, which is actually a constant and cannot modify the content. var declares variables that can be modified.
You do not need to give the value or the type of the variable, because the type can be inferred from an initialization, or an assignment expression.
If you specify a value or type of variable, type checking is performed, requiring that the types on both sides of an assignment expression match. For example, the assignment fails because the type does not match.
Val y:array[int]= x Slice (1, x.length-1) replace (",", "") Split ("")
<console>:37:error:type mismatch;
Found:array[string]
Required:array[int]
Val y:array[int]= x Slice (1, x.length-1) replace (",", "") Split ("")
Type Conversion Issues:
The above arrays are type-converted using map (_.toint)
An example of a single string conversion is "1". ToInt, here ToInt without parentheses.
The interesting thing is that when the numbers turn into strings, 1.toString, 1.toString () are all possible.
In Scala, type conversions are all methods, not forced type conversions.
Int to Long is used testint.tolong instead of C + + and Jaiva (long) testint
About function Call issues:
In the example above X.slice (1, x.length-1) can also be used x slice (1, x.length-1)
Scala calls a function to use the
A method B
can also be used
A. Method (b) when using. To refer to a method, you must use parentheses
It's OK
A method (b) uses an empty glyd to refer to the method, and if there is only one argument, the parentheses are not necessarily used. The above can also be a
Val y =x Slice (1, x.length-1) replace (",", "") Split ""
If there is a function with parameters, the call does not need to add (), such as 1.toString ()
Unlike Java, Scala supports rewrite operators. Scala has a companion object, the Apply method, which does not need to be displayed to write out the function name. It's a common way to build objects in Scala. For example
Array (1,4,5,16) returns an array with the Apply method of the array companion object, which looks similar to the constructor, but is not exactly.
Another example is "Hello" (4) Returning ' O ', actually calling the Def apply (N:int): Char method in the Stringops class.
Scala Learning Note 2 (with problem learning, gradually expands.) Understand thoroughly understand Scala.)