Scala 3中的类型推断更改 [英] Type inference changes in Scala 3
问题描述
Scala 3将带来类型推断的哪些变化?当前文档仅声明 TODO .例如,
What changes in type inference will Scala 3 bring? Currently documentation simply states TODO. For example,
Scala 2.13
Scala 2.13
scala> val i: Int = 42
val i: Int = 42
scala> val c: Char = 'a'
val c: Char = a
scala> List(i,c)
val res0: List[Int] = List(42, 97)
Scala 3(点数为0.24.0-RC1)
Scala 3 (dotty 0.24.0-RC1)
scala> val i: Int = 42
val i: Int = 42
scala> val c: Char = 'a'
val c: Char = a
scala> List(i,c)
val res0: List[AnyVal] = List(42, a)
平等
Scala 2.13
Equality
Scala 2.13
scala> 42 == Some(42)
^
warning: comparing values of types Int and Some[Int] using `==` will always yield false
val res2: Boolean = false
Scala 3
scala> 42 == Some(42)
1 |42 == Some(42)
|^^^^^^^^^^^^^^
|Values of types Int and Some[Int] cannot be compared with == or !=
推荐答案
So as for your Equality
example it is actually caused by the new Multiversal Equality which pretty much means that if you have an Eql[A, B]
where A is B then type A can only be compared to things it has an Eql
instance for them (of the form Eql[A, C]
or Eql[C, A]
).
就scala 3的通用类型推断而言,主要是:
In terms of general type inference for scala 3, the main things are:
-
联盟类型:我们可以现在表示联合类型和表达式,例如
Union Types: We can now represent union types and expressions like
if (condition) 1 else "1"
应推断为Int | String
类型.
显式null :联合类型的新用途之一是描述可为null的类型的方法,例如,我们可以用Java编写这样的代码:
Explicit Nulls: One of the new uses for union types is a way to describe nullable types, so for example we could write such a code in Java:
public String getUser(int id) {
if (id == 0) {
return "Admin";
}
return null;
}
在scala 2中,我们也可以这样写:
And also in scala 2 we could write:
def getUser(id: Int): String = if (id == 0) return "Admin" else null
但是在scala 3中,还必须将这种方法声明为String | Null
类型,以表示其可为空性,并且默认情况下在新版本的scala 3中将不会编译该方法.
But in scala 3 such a method will also have to be declared as of type String | Null
to represent its nullability, and will not compile by default in newer versions of scala 3.
使用Java时,它变得更加复杂,因此,如果您想了解更多有关Java的知识,建议您阅读链接.
When working with Java it gets more complicated so if you want to know more about it I suggest reading in the link.
GADT:类似于@functionalInterface
在Java中的工作方式,我们知道有GADT.
这意味着如果您要使用一种未实现的方法来实现特征:
GADT: Similar to how @functionalInterface
works in java we know have GADTs.
That means that if you were to have a trait with one unimplemented method:
trait Fooable {
def foo(): Unit
}
您可以通过传递带有该签名的lambda来创建它的实例,因此在此示例中:
You could create an instance of it by passing a lambda with that signature, so in this example:
val fooable: Fooable = () => print("Fooing")
There are a few more, including Context Functions, Implicit Conversions and Parameter untupling but those are the main ones.
这篇关于Scala 3中的类型推断更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!