小编Igo*_*jda的帖子

处理"智能投射不可行"的场景的最佳方法

我想知道处理这种情况的最佳方法是什么

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)

kotlin

6
推荐指数
1
解决办法
5897
查看次数

将这个java代码翻译成kotlin的最佳方式

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的最佳方法是什么?

kotlin

4
推荐指数
1
解决办法
365
查看次数

Kotlin Android扩展程序和菜单

有没有办法使用合成属性而不是使用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)

kotlin kotlin-android-extensions

3
推荐指数
1
解决办法
2677
查看次数

"接收器对象"和"扩展接收器"之间有什么区别吗

根据文档https://kotlinlang.org/docs/reference/extensions.html很难说出来

所以我想知道接收器对象扩展接收器是一样的吗?或者名称取决于上下文?

kotlin kotlin-extension

0
推荐指数
1
解决办法
313
查看次数

有没有更好的方法来访问可空属性?

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)

kotlin

0
推荐指数
1
解决办法
163
查看次数