Merge two sorted lists in Scala

def merge(xs1: Array[Int], xs2:Array[Int]): Array[Int] = {
        val len1 = xs1.length 
        val len2 = xs2.length 
        
        var i = 0
        var j = 0
        var k = 0
        var xs3: Array[Int] = new Array[Int](len1+len2) 
        while(i < len1 || j < len2)
        {
            if(i >= len1){ 
                xs3(k) = xs2(j) 
                j += 1
            }else if(j >= len2){
                xs3(k) = xs1(i) 
                i += 1 
            }else{
                if(xs1(i) < xs2(j)){
                    xs3(k) = xs1(i)
                    i += 1
                }else{
                    xs3(k) = xs2(j)
                    j += 1
                }
            }
            k += 1
        }
        return xs3
    }

map and flatMap in Scala

scala> def list[Int] = List(2, 3, 4)
list: [Int]=> List[Int]

scala> def f(v:Int) = List(1, 2, 3)
f: (v: Int)List[Int]

scala> list.map(x => f(x))
res10: List[List[Int]] = List(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5))

scala> list.flatMap(x => f(x))
res11: List[Int] = List(1, 2, 3, 2, 3, 4, 3, 4, 5)

scala> l.map(x => x)
res13: List[Int] = List(2, 3, 4)

scala> def f(x:Int) = if (x > 2) Some(x) else None
f: (x: Int)Option[Int]

scala> l.map(x => f(x))
res14: List[Option[Int]] = List(None, Some(3), Some(4))