Casting a java Object to Object[] in Scala

2019-06-16 21:12发布

问题:

Hi working on an Android SMS application in scala alls going fine expect I just cant find the way to write the following java code in scala. Any help appreciated

//---retrieve the SMS message received---
    Object[] pdus = (Object[]) bundle.get("pdus");  
    msgs = new SmsMessage[pdus.length];             
        for (int i=0; i<msgs.length; i++){  
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);   

I must admit I dont know how to write Object[] in scala its not java.util.ArrayList[java.lang.Object] I have tried using the Bundle.getStringArrayList to get a List[String] and the do a getBytes on the strings but that not working ... My last attempt was:

//I know I should be using an Option ...  
def getSmsListFromIntent(intent:Intent):List[SmsMessage]= {  
    val bundle = intent.getExtras()  
    var ret:List[SmsMessage]= null  
    if (bundle != null)   
        ret= for { pdu <- bundle.getStringArrayList("pdus").toList } yield  
SmsMessage.createFromPdu( pdu.getBytes())
    else ret= List()  
    ret  

java code comes from: http://mobiforge.com/developing/story/sms-messaging-android Thanks for any help

回答1:

The following answers the question in the title and may not be the best way to approach the problem. Take it for what it's worth.


The literal translation of a cast in Scala is asInstanceOf:

var x: Object = Array("foo", "bar");
var y = x.asInstanceOf[Array[Object]];    
>> x: java.lang.Object = Array(foo, bar)
>> y: Array[java.lang.Object] = Array(foo, bar)

However, as a fun exercise, why does this result in a ClassCastException?

var x: Object = Array(1, 2);
var y = x.asInstanceOf[Array[Object]];    

Happy coding



回答2:

Just for completness this is what I ended up writing with pst's suggestion:

    def getSmsListFromIntent(intent:Intent)= {
    val bundle = intent.getExtras()
        if (bundle != null) {
         bundle.get("pdus")
               .asInstanceOf[Array[Object]]
               .map(pdu => SmsMessage.createFromPdu( pdu.asInstanceOf[Array[Byte]] ))
        } else  Array[SmsMessage]()
}