Vandexel Vandexel - 1 year ago 132
Scala Question

simple scala help:llegal start of simple expression

I am learning scala and I think I don't understand something pretty basic. I haven't been able to find a clear answer to this online. I want to declare a variable within a function so that I can do some manipulations, as I will do in something like Python or Java. So, for example I declare this code outside of a function and it has no issues:

var myint = 10;

However, when I try to do any declaration, so for example declare the same variable inside a function:

def product [A,B](xs:List[A]) (ys:List[B]) =
var myint = 10;

I am getting "illegal start of simple expression". Why is this happening? What is the difference between declaring inside and outside of functions?

What I want to do overall is declare a new variable that takes these two lists and creates a list of lists. So if xs = [1,2] and ys = [6,7], I want to create a variable that is [[1,2][6.7]]. How could I create this variable inside the product function?

Thank you so much!

Answer Source

You don't need a variable. Just return the new list of lists. (You also don't need semicolons.)

def product[A](xs: List[A], ys: List[A]): List[List[A]] = 

Scala is a statically typed language. It keeps a close eye on the type of all elements, arguments, return types, etc. Notice how the return type changes if the two lists are of different types.

def product[A,B](xs: List[A], ys: List[B]): List[List[Any]] =

This amounts to a loss of type information, which usually leads to bad outcomes. Avoid it.