我想知道处理这种情况的最佳方法是什么
class Person(var name:String? = null, var age:Int? = null){
fun test(){
if(name != null && age != null)
doSth(name, age) //smart cast imposible
}
fun doSth (someValue:String, someValue2:Int){
}
}
Run Code Online (Sandbox Code Playgroud)
调用doSth方法并确保名称和年龄为nt null的最简单方法是什么?
我正在寻找一些简单的东西,就像一个变量场景我只想使用let
name?.let{ doSth(it) }
Run Code Online (Sandbox Code Playgroud) URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream in = connection.getInputStream();
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
Run Code Online (Sandbox Code Playgroud)
我对这部分特别好奇
while(bytesRead = in.read(buffer))
Run Code Online (Sandbox Code Playgroud)
我们知道,在kotlin中,asigements被视为语句,而在java中,它们被视为表达式,因此这种结构只能在java中使用.
将这个java代码翻译成kotlin的最佳方法是什么?
有没有办法使用合成属性而不是使用findItem方法访问fragment_photo_gallery布局中定义的menu_item_search菜单项?
override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
super.onCreateOptionsMenu(menu, menuInflater)
menuInflater.inflate(R.menu.fragment_photo_gallery, menu)
//is there a way to access searchItem using synthetic properties?
val searchItem = menu.findItem(R.id.menu_item_search)
}
Run Code Online (Sandbox Code Playgroud) 根据文档https://kotlinlang.org/docs/reference/extensions.html很难说出来
所以我想知道接收器对象和扩展接收器是一样的吗?或者名称取决于上下文?
将sound.id属性从nullable 转换为nonnulable并将其作为play方法传递的最佳方法是什么?
class Sound() {
var id: Int? = null
}
val sound = Sound()
...
//smarcat imposible becouse 'sound.id' is mutable property that
//could have changed by this time
if(sound.id != null)
soundPool.play(sound.id, 1F, 1F, 1, 0, 1F)
//smarcat imposible becouse 'sound.id' is mutable property that
//could have changed by this time
sound.id?.let {
soundPool.play(sound.id, 1F, 1F, 1, 0, 1F)
}
Run Code Online (Sandbox Code Playgroud)