How to optionally wrap the return value of a Java function that may return null

Asked 1 years ago, Updated 1 years ago, 74 views

If you want to receive an option for a function that may return null, for example,

valfuge=Option(nullablefunc())
defaultwice(one:Option [Int]) = {
    one.map(2*)
}
value result=twice (fuge.asInstanceOf [Option [Int]])

In the case of Option(null), the type will be Option[Null]=None, so I cast it to make it Option[Int], but

 fuge.asInstanceOf [Option [Int]]

If there is a possibility that the option will receive null, is there any other way I can receive null?

scala

2022-09-30 17:58

2 Answers

If you want to use the return value of the java function nullfunc() that returns null or Int as the Option [Int] type,

 value: Option [Int] = Option (nullablefunc())

I think it will be solved if you add a signature like this.


2022-09-30 17:58

In scala, if it's null at Integer=>Int, it seems that NullPointerException will be issued.

scala>valx:java.lang.Integer=null
x —Integer=null

scala>value —Int=x
java.lang.NullPointerException
  atscala.Predef$.Integer2int (Predef.scala:357)
  ... 43elided

So the above code is

 value = Option [Integer] (nullablefunc()) .map (Integer 2 int)
defaultwice(one:Option [Int]) = {
    one.map(2*)
}
val result=twice(fuge)

Otherwise, NullPointerException will appear


2022-09-30 17:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.