什么是类型,什么是scala中的类型构造函数

Bog*_*nko 14 scala

我有点困惑的东西理解typescala手段.

在文档中,我读到的List[Int]是一个类型,List是一个类型构造函数.

type但当我写下以下内容时,关键字是什么意思?

val ls: scala.collection.immutable.List.type = scala.collection.immutable.List
Run Code Online (Sandbox Code Playgroud)

例如,与此type相关的type内容可以定义为特征中的字段.

Gab*_*lla 11

什么关键字类型意味着我写下以下内容

typeobjectScala中定义的成员.

假设您有一个类及其伴随对象:

class Foo(a: String)

object Foo {
  def apply(a: String) = new Foo(a)
}
Run Code Online (Sandbox Code Playgroud)

现在假设您要编写一个接受该对象Foo作为输入的方法.它的类型是什么?

如果你这样写:

def someMethod(fooObj: Foo) = fooObj.apply("x") // doesn't compile
Run Code Online (Sandbox Code Playgroud)

它不会编译.Foo指的是类的实例的类型(即由new Foo("x")or 返回的类型Foo("x")).这就是为什么对象有一个type可以引用自己类型的成员:

def someMethod(fooObj: Foo.type) = fooObj.apply("x") // compiles!
Run Code Online (Sandbox Code Playgroud)

在您的具体示例中List.type是伴随对象的类型List.这里有几个例子,我希望能澄清它的含义:

val listObj: List.type = List
val anEmptyList: List[Int] = listObj.empty[Int] // List()
val aListOfIntegers: List[Int] = listObj.range(1, 4) // List[(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

以及这种类型如何与可以定义为特征中的字段的类型相关联.

type关键字定义一种类型的构件..type 一个类型的成员.从概念上讲,它就像Scala中的每个对象都有一个名为type的类型成员,如下所示:

object Foo {
  type type = Foo
}
Run Code Online (Sandbox Code Playgroud)

显然这不会编译,但它会让你知道它可能是什么样子.


oxb*_*kes 10

val像上面这样的scala 赋值中:

val name: Tpe = expression
Run Code Online (Sandbox Code Playgroud)

Tpe是标识符的类型name.因此:

val x: List.type = List
Run Code Online (Sandbox Code Playgroud)

List 对象的类型(也就是List模块List伴侣)是List.type.这表明它是一个单身人士.所有这些都与类型理论中的类型构造函数的概念完全正交.

键入构造函数

在类型理论中,List(注意:不是伴侣)既是类型(表示*)又是类型构造函数(表示* -> *),因为当你向List(例如Int)提供类型参数时,你有一个类型(即List[Int]).Scala为此构造提供了语法.例如:

def foo[F[_]]: F[Int]
        ^^^^     ^^^
         |        + supply a type argument to F[_]  
         |
         + the type constructor F[_] 
Run Code Online (Sandbox Code Playgroud)

但除非你了解更多,否则你无法真正实现这样的方法F.例如,如果存在隐式scalaz.Monad[F],则可以使用该Monad.pure值来构造您的F[Int]喜欢:

def foo[F[_]: Monad]: F[Int] = Monad[F].pure(1)
Run Code Online (Sandbox Code Playgroud)

在斯卡拉

Scala确实允许您将List类型构造函数作为类型参数传递给此类方法.例如:

scala> def foo[F[_]]: F[Int] = ???
foo: [F[_]]=> F[Int]

scala> lazy val x = foo[List]
x: List[Int] = <lazy>
Run Code Online (Sandbox Code Playgroud)

然而,List你在供应foo[List]不是同伴

请注意声明foo将导致以下警告:

<console>:11: warning: higher-kinded type should be enabled
by making the implicit value scala.language.higherKinds visible.
This can be achieved by adding the import clause 'import 
scala.language.higherKinds'
or by setting the compiler option -language:higherKinds.
See the Scaladoc for value scala.language.higherKinds for a discussion
why the feature should be explicitly enabled.
       def foo[F[_]]: F[Int] = ???
               ^
Run Code Online (Sandbox Code Playgroud)