Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast Scala value already defined in the function

Tags:

scala

how to convert a value when using it? Example:

scala> def sum(x:Double, y:Int) {
     | x + y
     | }
sum: (x: Double,y: Int)Unit

scala> println(sum(2,3))
()

How to modify the line with println to print the correct number?

Thanks

like image 574
adelarsq Avatar asked Dec 05 '22 01:12

adelarsq


2 Answers

Note that sum returns Unit:

sum: (x: Double,y: Int)Unit

This happens because you missed an equal sign between method declaration and body:

def sum(x:Double, y:Int) {

You should have declared it like this:

def sum(x:Double, y:Int) = {
like image 56
Daniel C. Sobral Avatar answered Dec 23 '22 06:12

Daniel C. Sobral


Your problem is not with casting but with your function definition. Because you ommitted the = before the function parameters and the function body, it returns Unit (i.e. nothing), as the REPL told you: sum: (x: Double,y: Int)Unit. Simply add the equals:

def sum(x: Double, y: Int) = {
  x + y
}

Now your sum method will return a Double.

like image 23
pr1001 Avatar answered Dec 23 '22 07:12

pr1001