首页 > 解决方案 > 如何将这段代码从 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 方法之前被调用。

标签: androidinheritancekotlin

解决方案


您可以使用@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
}

推荐阅读