2011-09-13 13 views
8

Ciao lavoro su un'applicazione Android SMS in scala all va tutto bene aspettarsi che non riesco a trovare il modo di scrivere il seguente codice Java in scala. Qualsiasi aiuto apprezzatoLancio di un oggetto java su oggetto [] in Scala

//---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]); 

Devo ammettere che non so come scrivere Object [] a Scala la sua non java.util.ArrayList [java.lang.Object] Ho provato con il Bundle.getStringArrayList per ottenere un List [String] e fare un getBytes sulle corde, ma che non funziona ... il mio ultimo tentativo è stato:

//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 

codice Java viene da: http://mobiforge.com/developing/story/sms-messaging-android Grazie per qualsiasi aiuto

risposta

11

Th La seguente risposta è la domanda nel titolo e potrebbe non essere il modo migliore per affrontare il problema. Prendilo per quello che vale.


La traduzione letterale di un cast in Scala è 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) 

Tuttavia, come un esercizio divertente, perché questo risultato in una ClassCastException?

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

Felice di codifica

+0

Grazie PST, questo è quello di cui avevo bisogno! – user433320

0

Solo per completezza questo è quello che ho finito per scrivere con il suggerimento di pst:

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]() 
} 
Problemi correlati