简体   繁体   English

Scala 定义自定义类型 - 类型不匹配错误

[英]Scala Defining Custom Type - Type Mismatch Error

I am doing a basic exercise to understand scala user defined types.我正在做一个基本练习来了解 scala 用户定义类型。 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?有没有办法让 Scala 可以自动确定类型而无需指定确切的参数类型? 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 f1 Int explicitly, I can just do f1(...) and it works.在这种情况下,我不需要显式调用 f1 Int ,我只需执行 f1(...) 即可。

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.您可以检查g: MyType[Int]是否编译。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM