Scala toInt is not a member of Any

The following code works println (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 to a function (as indicated above), it does not work. He says: "The value of toInt is not a member of Any"

When I remove toInt, it says:

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

e - Map as shown below

  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 top10Tweets,

 def top10Tweets(tweets: String, retweet_c: Int, mention_c: Int) = { } 
+7
casting types scala option
source share
3 answers

change

Well, with the new information, I would suggest you create a case class that stores data instead of using Map , so you save type information. I know that distributing hashes / maps for them in dynamically typed languages, but in statically typed languages ​​like scala data types are the preferred way.

orig

Since I do not know what e , and what is the signature of top10Tweets , I can only guess. But from your code and error, I assume that e is Map[String, String] , and you are trying to get the string representation of the integer for the key "retweets" and convert it to Int . You pass Int as the default value, so the inferencer type introduces the Any type, because it is the most common type of Super String and Int . However, Any does not have a toInt method and, therefore, you get an 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 enter the default value as String , or change the value of "retweets" to Int earlier if it exists:

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

In any case, a little more information will help give an accurate answer.

+6
source share

Yes, because in Map "string" β†’ "string", and you did when getOrElse (else) string β†’ int, that's why its Any.

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

works fine or you can:

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

The same problem bothers me before you can check below

 Map("x" -> 2).getOrElse[Int](x, 4) 
0
source share

All Articles