铸造一个Java对象为Object []斯卡拉 [英] Casting a java Object to Object[] in Scala
问题描述
喜上阶承滴盘喽一个Android SMS应用工作的期待我只是无法找到写在斯卡拉以下Java code的方式。任何帮助AP preciated
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]);
我必须承认,我不知道怎么写对象[]斯卡拉它不是java.util.ArrayList中的[java.lang.Object继承]
我已经使用Bundle.getStringArrayList得到一个列表[字符串]尝试和对字符串做的getBytes但没有工作...
我最后的尝试是:
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来源于: http://mobiforge.com/developing/故事/短信通讯功能的Android
感谢您的帮助。
java code comes from: http://mobiforge.com/developing/story/sms-messaging-android Thanks for any help
推荐答案
如下回答标题中的问题,可能不是解决这个问题的最好办法。以它为它的价值。
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.
在斯卡拉铸造的直译就是 asInstanceOf
:
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)
但是,作为一个有趣的练习,为什么在一个ClassCastException做这样的结果?
However, as a fun exercise, why does this result in a ClassCastException?
var x: Object = Array(1, 2);
var y = x.asInstanceOf[Array[Object]];
快乐编码
这篇关于铸造一个Java对象为Object []斯卡拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!