Как я обхожу стирание типа на Scala? Или, почему я не могу получить параметр типа своих наборов?

Вы можете использовать PercentRelativeLayout . Это недавнее недокументированное дополнение к библиотеке поддержки проектирования , позволяющее задавать не только элементы относительно друг друга, но и общий процент доступного пространства.

Подкласс RelativeLayout, который поддерживает измерения и поля в процентах. Вы можете указать измерение или поле дочернего элемента, используя атрибуты с суффиксом «Процент».


  

Пакет Percent предоставляет API-интерфейсы для поддержки добавления и управления измерениями на основе процента в вашем приложении.

Для использования вам необходимо добавить эту библиотеку в список зависимостей Gradle :

dependencies {
    compile 'com.android.support:percent:22.2.0'//23.1.1
}

366
задан Daniel C. Sobral 7 July 2009 в 08:03
поделиться

1 ответ

This answer uses the Manifest-API, which is deprecated as of Scala 2.10. Please see answers below for more current solutions.

Scala was defined with Type Erasure because the Java Virtual Machine (JVM), unlike Java, did not get generics. This means that, at run time, only the class exists, not its type parameters. In the example, JVM knows it is handling a scala.collection.immutable.List, but not that this list is parameterized with Int.

Fortunately, there's a feature in Scala that lets you get around that. It’s the Manifest. A Manifest is class whose instances are objects representing types. Since these instances are objects, you can pass them around, store them, and generally call methods on them. With the support of implicit parameters, it becomes a very powerful tool. Take the following example, for instance:

object Registry {
  import scala.reflect.Manifest

  private var map= Map.empty[Any,(Manifest[_], Any)] 

  def register[T](name: Any, item: T)(implicit m: Manifest[T]) {
    map = map.updated(name, m -> item)
  }

  def get[T](key:Any)(implicit m : Manifest[T]): Option[T] = {
    map get key flatMap {
      case (om, s) => if (om <:< m) Some(s.asInstanceOf[T]) else None
    }     
  }
}

scala> Registry.register("a", List(1,2,3))

scala> Registry.get[List[Int]]("a")
res6: Option[List[Int]] = Some(List(1, 2, 3))

scala> Registry.get[List[String]]("a")
res7: Option[List[String]] = None

When storing an element, we store a "Manifest" of it too. A Manifest is a class whose instances represent Scala types. These objects have more information than JVM does, which enable us to test for the full, parameterized type.

Note, however, that a Manifest is still an evolving feature. As an example of its limitations, it presently doesn't know anything about variance, and assumes everything is co-variant. I expect it will get more stable and solid once the Scala reflection library, presently under development, gets finished.

241
ответ дан 23 November 2019 в 00:09
поделиться
Другие вопросы по тегам:

Похожие вопросы: