Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala value toInt is not a member of Any

The println in the following code works (with or without toInt)

println("retweets : ", e.getOrElse("retweets", 0).toInt)

top10Tweets(""+e.get("text").get, e.getOrElse("retweets", 0).toInt)

But when I pass it as an argument of a function (as above), it does not work. It says "value toInt is not a member of Any"

When I remove toInt, it says,

    type mismatch;
[error]  found   : Any
[error]  required: Int

e is a Map, as follows,

  def tweetDetails(obj: twitter4j.Status) = {
   Map(
   "id" -> obj.getUser().getId(),
   "screenName" -> obj.getUser().getScreenName(),
   "text" -> obj.getText(),
   "retweets" -> obj.getRetweetCount(),
   "mentions" -> obj.getUserMentionEntities().length)
  }

signature of top10Tweets,

def top10Tweets(tweets: String, retweet_c: Int, mention_c: Int) = {
}
like image 661
user644745 Avatar asked Jul 16 '13 10:07

user644745


2 Answers

edit:

Ok, with the new information I would suggest you to create a case class that holds the data instead of using a Map, this way you will preserve type information. I know it is common to use hashes/maps for that in dynamically typed languages, but in statically typed languages as scala data types are the preferred way.

orig:

As I neither know what e is, nor what signature top10Tweets has, I can only assume. But from your code and the error I assume that e is a Map[String, String] and you are trying to get the string representation of an integer for the key "retweets" and convert it to an Int. As a default value you pass in an Int, so the type inferencer infers type Any, because that is the most common super type of String and Int. However Any does not have a toInt method and thus you get the error.

Map("x" -> "2").getOrElse("x", 4).toInt
<console>:8: error: value toInt is not a member of Any
              Map("x" -> "2").getOrElse("x", 4).toInt

Either pass in the default value as String, or convert the value of "retweets" to an Int before, if it exists:

e.get("retweets").map(_.toInt).getOrElse(0)

Anyway a little more information would help to give an accurate answer.

like image 101
drexin Avatar answered Sep 20 '22 19:09

drexin


Yes because in Map is "string" -> "string" and You did when getOrElse ( else ) string -> int, thats why its Any.

Map("x" -> 2).getOrElse("x", 4).toInt

works fine or You can:

Map("x" -> "2").getOrElse("x", "4").toInt
like image 32
daaatz Avatar answered Sep 18 '22 19:09

daaatz