android - 如何将这段代码从 Java 翻译成 Kotlin?
问题描述
我正在尝试将这段代码从 Java 转换为 Kotlin。但是,我正在努力处理接收整数作为参数的第二个构造函数的“超级”调用。
package info.androidhive.volleyexamples.volley.utils;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
@Override
public Bitmap getBitmap(String url) {
return get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
到目前为止我已经做到了。如您所见,LruCache 要求您将某些内容作为参数传递。但我想用“getDefaultLruCacheSize”方法计算这个参数。
class LruBitmapCache(var maxSize: Int = 0) : LruCache<String, Bitmap>(maxSize), ImageCache {
private fun getDefaultLruCacheSize(): Int {
val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
return maxMemory / 8
}
init {
maxSize = getDefaultLruCacheSize()
}
override fun sizeOf(key: String?, value: Bitmap?): Int = if (value != null) {
(value.rowBytes * value.height / 1024)
} else{
val defaultValue = 1
defaultValue
}
override fun getBitmap(url: String?): Bitmap? = get(url)
override fun putBitmap(url: String?, bitmap: Bitmap?) {
put(url, bitmap)
}
问题是,在我目前的方法中,super 在我的 init 方法之前被调用。
解决方案
您可以使用@JvmOverloads
和使用缓存的默认值,因此您不需要显式定义第二个构造函数:
class LruBitmapCache @JvmOverloads constructor(
sizeInKiloBytes: Int = defaultLruCacheSize
) : LruCache<String, Bitmap>(sizeInKiloBytes), ImageCache {
protected fun sizeOf(key: String, value: Bitmap): Int = value.rowBytes * value.height / 1024
fun getBitmap(url: String): Bitmap = get(url)
fun putBitmap(url: String, bitmap: Bitmap) {
put(url, bitmap)
}
companion object {
val defaultLruCacheSize: Int
get() {
val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
return maxMemory / 8
}
}
}
如果你想使用第二个构造函数,你需要这样做
class LruBitmapCache(
sizeInKiloBytes: Int
) : LruCache<String, Bitmap>(sizeInKiloBytes), ImageCache {
constructor(): this(defaultLruCacheSize)
// omitted for brevity
}
推荐阅读
- javascript - 下载大型 CSV 文件 - href 无意中截断结果
- c# - 使用 Admob for Unity 显示奖励广告/插页式广告时的 ARCore 会话/锚点跟踪
- postgresql - 如何将虚拟表中的值获取到变量?
- php - 我可以拆分这个字符串以获得我需要的信息吗?
- python - 如何使用从另一个具有主要功能的程序导入?
- c# - Caliburn Micro,在 nedsted 对象中的属性更改时通知
- puppet - 如何从这个复杂的 Puppet 结构中提取值
- ansible - 如何使用 Ansible 或 Jinja2 在变量名中转义冒号(“:”)?
- javascript - 迭代给定参数的方法
- javascript - 函数引用未定义的本地对象 React