Reputation: 5401
I have code like this
object API {
val apiBaseUrl = "https://api.com/2/"
def getUserDetails(id: String, pass: String): Map[String, String] {
val apiRequestUrl = apiBaseUrl + "?id=" + id + "&pass=" + pass
}
}
This gives me error only classes can have declared but undefined members
for line starting with def
and error only declarations allowed here
for line starting with val apiRequestUrl
. But when i change the above code to(just put an equals sign after the method signature)
object API {
val apiBaseUrl = "https://api.com/2/"
def getUserDetails(id: String, pass: String): Map[String, String] = {
val apiRequestUrl = apiBaseUrl + "?id=" + id + "&pass=" + pass
}
}
there is no error. Is there a difference between the above 2 definitions?
Upvotes: 3
Views: 3592
Reputation: 7266
Is there a difference between the above 2 definitions?
Yes. In Scala, you have to use an equals sign for method bodies that return a value. So your second code fragment is more correct.
The first code fragment is parsed like this, I believe:
object API {
val apiBaseUrl = "https://api.com/2/"
def getUserDetails(id: String, pass: String): Map[String, String]
{
val apiRequestUrl = apiBaseUrl + "?id=" + id + "&pass=" + pass
}
}
This explains the error about the missing body for getUserDetails
and the error about the block { ... }
where a declaration is expected.
Upvotes: 5