Scala Modifiers and Type parametrization

前端 未结 3 953
日久生厌
日久生厌 2021-02-13 12:35

I\'m creating a memoization class.

Each class memoizes a function type and has the following definition:

 class MemoizedFunction1[-T1, +R](f: T1 => R)         


        
3条回答
  •  抹茶落季
    2021-02-13 13:05

    Let's assume you can remove [this].

    Without [this] you can add method getOtherCache:

    class MemoizedFunction1[-T1, +R](f: T1 => R) { 
      private val cache = mutable.Map[T1, R]() // trait Map[A, B] extends Iterable[(A, B)] with Map[A, B] with MapLike[A, B, Map[A, B]]
      def apply(t: T1): R = cache.getOrElseUpdate(t,f(t))
    
      def getOtherCache(other: MemoizedFunction1[T1, R]) {
        val otherCache: mutable.Map[T1, R] = other.cache;
      }
    }
    
    class A
    class B extends A
    
    val mf1: MemoizedFunction1[B, B] = new MemoizedFunction1[B, B](b => b)
    
    val mf2: MemoizedFunction1[B, B] = new MemoizedFunction1[A, B](a => new B)
    // mf2 is MemoizedFunction1[B, B]
    // mf2 contains mutable.Map[A, B]
    
    mf1.getOtherCache(mf2) //Error! mf2.cache is NOT mutable.Map[B, B]!
    

提交回复
热议问题