For a function that gets called twice for every row, this can be very slow (the unnecessary pattern matching). Perhaps create 5 writable cloning functions, and create a function that picks the right cloning function given the classtag, and use the picking function outside the loop (in HadoopRDD).