How to convert a scala Int to a java Integer?

Goldengirl :

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.

rleibman :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=451942&siteId=1