Domanda

Straight forward problem that I don't see what I'm doing wrong in - some type mismatch somewhere. Basically trying to set a default datatype of Long on parameters that are coming in from a web request. Here's the code:

val startTs:Long = params.getOrElse("start_ts", DateTime.yesterdayAsEpoch).toLong
val endTs:Long = params.getOrElse("end_ts", DateTime.todayAsEpoch).toLong

My DateTime helper code:

def todayAsEpoch: Long = {
    val c = Calendar.getInstance(TimeZone.getTimeZone("EST"))
    c.setTime(new java.util.Date())
    c.set(c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH),0,0,0)
    c.getTimeInMillis / 1000L
  }

  def yesterdayAsEpoch: Long = {
    val c = Calendar.getInstance(TimeZone.getTimeZone("EST"))
    c.setTime(new java.util.Date())
    c.set(c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH),0,0,0)
    ((c.getTimeInMillis / 1000L) - 86400)
  }

And finally, the error:

value toLong is not a member of Any
[error]         val startTs:Long = params.getOrElse("start_ts", DateTime.yesterdayAsEpoch).toLong
[error]                                                                                    ^
[error] /vagrant/src/main/scala/com/myapp/api/controllers/FooController.scala:437: value toLong is not a member of Any
[error]         val endTs:Long = params.getOrElse("end_ts", DateTime.todayAsEpoch).toLong
[error]                                                                            ^
[error] two errors found
[error] (compile:compile) Compilation failed
È stato utile?

Soluzione

You did not say what params is. It looks like it might be a Map[String, X] with some type X. params.getOrElse(key, someLong) will considered to have the best common supertype of X and Long which happens to be Any, according to the error message, and which has no toLong method. As your default value happens to be Long already, and so don't need to be converted, I guess there is a toLong method on X.

If it is so, then you should convert the value retrieved from params to Long (when there is such a value), before providing the default value. That would be :

params.get("key").map(_.toLong).getOrElse(defaultValue)

Altri suggerimenti

I'm guessing params is a Map[String, Something], and that Something isn't always a numeric type. (String?) In any case, when you call params.getOrElse, it's inferring a common type between Something and Long, and finding Any, which is why you can't call toLong on it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top