scalagenericstypesscala-collectionscustom-type

Scala Defining Custom Type - Type Mismatch Error


I am doing a basic exercise to understand scala user defined types. Consider the following example:

type MyType[T <: AnyVal] = (List[Seq[T]], String, String)
val g: MyType = (List(Seq(1, 2), Seq(3, 4), (Seq(5, 6))), "foo", "bar")

This fails to compile, with type error:

type MyType takes type parameters
[error]     val g: MyType = (List(Seq(1, 2), Seq(3, 4), (Seq(5, 6))), "foo", "bar")

However, this compiles:

type MyType[T <: AnyVal] = (List[Seq[T]], String, String)
val g: MyType[Int] = (List(Seq(1, 2), Seq(3, 4), (Seq(5, 6))), "foo", "bar")

Is there a way so that Scala can automatically determine the type without needing to specify the exact paramter type? I know for functions we can do the following:

import scala.reflect.ClassTag

def f1[T](lst: List[T])(implicit ev: ClassTag[T]) = {
  lst.toArray
}

In which case I do not need to call f1Int explicitly, I can just do f1(...) and it works.


Solution

  • You can just write

    val g = (List(Seq(1, 2), Seq(3, 4), (Seq(5, 6))), "foo", "bar")
    

    and compiler will infer the type. You can check that g: MyType[Int] compiles.

    Also you can do

    def TypeOf[F[_ <: AnyVal]] = new PartiallyAppllied[F]
    class PartiallyAppllied[F[_ <: AnyVal]] {
      def apply[A <: AnyVal](fa: F[A]) = fa
    }
    
    val g = TypeOf[MyType]((List(Seq(1, 2), Seq(3, 4), (Seq(5, 6))), "foo", "bar"))
    
    g: MyType[Int]