adelarsq
adelarsq

Reputation: 3738

How to cast Scala value already defined in the function

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

Upvotes: 4

Views: 516

Answers (2)

pr1001
pr1001

Reputation: 21962

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.

Upvotes: 6

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297285

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) = {

Upvotes: 10

Related Questions