0

Is there a way I can make a function in scala wherein I can enter various types of parameter inputs? Please refer to the sample code below. I want to make the code below into one function that would accept various data types for the input.

Example:

/** */
def toMatrix(A: Array[Double], m:Int, n:Int): Array[Array[Double]] = {
    var A_ = Array.apply(A.slice(0,n),A.slice(n*1,n*1+n))
    for (i <- 2 to (m-1)){
        A_ = A_ ++ Array(A.slice(n*i,(n*i)+n))
        }
    A_
}


/** */
def toMatrixInt(A: Array[Int], m:Int, n:Int): Array[Array[Int]] = {
    var A_ = Array.apply(A.slice(0,n),A.slice(n*1,n*1+n))
    for (i <- 2 to (m-1)){
        A_ = A_ ++ Array(A.slice(n*i,(n*i)+n))
        }
    A_
}

/** */
def toMatrixBoolean(A: Array[Boolean], m:Int, n:Int) = {
    var A_ = Array.apply(A.slice(0,n),A.slice(n*1,(n*1)+n))
    for (i <- 2 to (m-1)){
        A_ = A_ ++ Array(A.slice(n*i,(n*i)+n))
        }
    A_
}

2 Answers 2

3

Yes. And you also don't need mutable variable and ugly imperative loops :) If you are using scala syntax, might as well take a moment or two to learn actually using the language :/

def toMatrix[T : ClassTag](a: Array[T], m:Int, n:Int) = a.grouped(n).toArray
Sign up to request clarification or add additional context in comments.

Comments

1

Obviously you are talking about type parametrization, or generics in Java world. You should go and read about it -- there are a lot of information in internet and books on the subject. Some examples from alvinalexander.com:

http://alvinalexander.com/scala/scala-classes-using-generic-types-examples

I personally recommend you the book Programming in Scala by Martin Odersky et al. It is slightly old now, but it is perfectly written and thoroughly covers the language.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.