I am executing the following code:
def takeN(s : String, n : Int): String = {
var j = 1
var o = s.split("")
if(n != 0){
var arr = new Array[Char](n)
}
while(j <= n){
arr(j) = o(j)
j += 1
}
val ml = List.fromArray(arr)
var newS = ml.mkString("")
newS
}
When I test this code with this takeN(“abcd”,2), the answer that I am getting is this:
nullab
When I run this code at: http://www.simplyscala.com/ everything works but when I try it at my home pc I get errors so I changed it to :
def takeN(s : String, n : Int): String = {
var j = 1
var o = s.split("")
var arr = new Array[Char](n)
while(j <= n){
arr(j) = o(j)
j += 1
}
val ml = List.fromArray(arr)
var newS = ml.mkString("")
newS
}
then I get this error:
error: type mismatch;
found : java.lang.String
required: Char
arr(j) = o(j)
I am not sure how to fix this. why scala is so hard??
You can write a recursive answer without all that vals and vars. Most code is to guard agains invalid input:
A shorter solution (but without guard) is:
usage:
But let’s try an solution closer to your approach:
String indexes start (as in Java) with 0, and so we go to j < n, not j <= n and from 0, not 1. We don’t need ‘o’ (with dubious split (“”), since we can use s(j) instead too.
Next step, get rid of the intermediate List:
We simplified the return. Now let’s use a for-loop, instead of the while:
or just