PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How to convert a scala Int to a java Integer?

 July 21, 2022     int, integer, java, scala     No comments   

Issue

I am reasonable new to scala and working with scala and Java together.

I am trying to pass a scala Int into a method that accepts an Integer(java.long.Integer). Since they are of different types the compiler gives an error.

 /* name- Option[String], id- Option[Integer] , mask- Option[String]*/
 new findingFrame(name,id, mask)

 case class findingFrame(name: String,
                         id: Option[java.lang.Integer],
                         mask : Option[String])

I tried using .instanceOf [java.lang.Integer], but this doesn't work either..

I am not sure how to solve this.. Can somebody help me please? Thank you.


Solution

I think most other answers cover it, your issue is with the use of Option, not with the difference between scala and java integers. There's many things you can do with options, for example: Given:

val optionOfInteger = Option(5)
  • (ugly) assume your option always has a value, just use get (val i = optionOfInteger.get)
  • Apply a default value: (val i = optionOfInteger.getOrElse(0))
  • You can map the Option of integer into option of something else (val optionOfString = optionOfInteger.map(_.toString))
  • You can do both of the last two in one call ( val str = optionOfInteger.fold("Nothing")(_.toString) )
  • You can also think of Option as a collection of one, so all the nice stuff you can do with collections you can do with Options, including converting it to other type of collections, fold it, etc. A good use for it in your case, might be to make the decision to call or NOT to call the java method.

def myFn(findingFrame: FindingFrame) = { findingFrame.in.foreach{i => javaMethod(i) } }

In the above you could use map, or match/case instead.



Answered By - rleibman
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing