user1269298
user1269298

Reputation: 727

function not indicate return type - Scala

I am new to scala. In tutorial I saw the way to define a function is

def functionName ([list of parameters]) : [return type] = {...}

But in other's code I saw following example that function did not indicate return type. Why is this?

  def parseLine(line:String) = {
    val fields = line.split(",")
    val stationID = fields(0)
    val entryType = fields(2)
    val temperature = fields(3).toFloat * 0.1f * (9.0f / 5.0f) + 32.0f
    (stationID, entryType, temperature)
  }

Upvotes: 0

Views: 41

Answers (1)

prayagupadhyay
prayagupadhyay

Reputation: 31222

If there's no return type the last expression is return value.

example,

scala> def doSomething = "i will be returned"
doSomething: String

you can see in above example though there's no return type mentioned, it will take String as return type.

Also if the method is returning based on conditions, scalac will figure itself out the return type.

scala> def doSomething = if(1 == 1) "i will be returned" else 2
doSomething: Any

scala> doSomething
res10: Any = i will be returned

Also read - Return in Scala

Upvotes: 2

Related Questions