我正在尝试将这段代码从Java转换为Kotlin。但是,我正在努力处理第二个接受整数作为参数的构造函数的“ super”调用。
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方法之前调用的。
答案 0 :(得分:2)
您可以使用@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
}