我正在查看页面Dotty
下的文档Contextual Abstractions
,我看到了Given Instances
.
给定实例(或简单地说,“给定”)定义了某些类型的“规范”值,用于将参数合成给给定的子句。例子:
trait Ord[T] {
def compare(x: T, y: T): Int
def (x: T) < (y: T) = compare(x, y) < 0
def (x: T) > (y: T) = compare(x, y) > 0
}
given intOrd: Ord[Int] {
def compare(x: Int, y: Int) =
if (x < y) -1 else if (x > y) +1 else 0
}
given listOrd[T]: (ord: Ord[T]) => Ord[List[T]] {
def compare(xs: List[T], ys: List[T]): Int = …
Run Code Online (Sandbox Code Playgroud) 有没有办法像在 Java 中一样覆盖 Scala 3 枚举中的方法?
public enum Test {
ONE {
@Override
public int calc() {
return 1;
}
},
TWO {
@Override
public int calc() {
return 2;
}
};
public abstract int calc();
}
Run Code Online (Sandbox Code Playgroud)
我试过这样的事情,但没有结果。在文档中也没有找到关于枚举方法覆盖的任何内容。
enum Test {
def calc(): Int ={
0
}
case One
override def calc(): Int ={
1
}
case Two
override def calc(): Int ={
2
}
}
Run Code Online (Sandbox Code Playgroud)
也许有另一种方法可以实现类似的功能?
我想关注有关 Scala[1] 的书,但它使用 Scala 3,而我安装了 Scala 2。我想使用这两个版本,类似于python2
和的版本python3
。
我尝试使用官方源在本地安装 Scala3 ,但我只能掌握项目级别的工作目录。该sbt
提示不像 REPL 那样工作,我只能使用 Scala 2 打开 REPL(我每次都检查版本)。
无法卸载Scala2,如何打开Scala3的REPL?
我只是想使用 akka 在 scala 项目中实现一个小示例 REST 端点。代码如下
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import scala.io.StdIn
import scala.concurrent.ExecutionContextExecutor
object ViewAPI :
@main def run(): Unit = {
implicit val system = ActorSystem(Behaviors.empty, "my-system")
implicit val executionContext = system.executionContext
val route =
path("hello") {
get {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
}
}
val bindingFuture = Http().newServerAt("localhost", 9001).bind(route)
}
Run Code Online (Sandbox Code Playgroud)
我的 sbt 文件如下所示:
libraryDependencies += ("com.typesafe.akka" %% "akka-http" % "10.2.9").cross(CrossVersion.for3Use2_13)
libraryDependencies += "com.typesafe.akka" %% "akka-actor-typed" % "2.6.19"
libraryDependencies += "com.typesafe.akka" …
Run Code Online (Sandbox Code Playgroud) 这是基本设置:
trait MyProduct[A, B](a: A, b: B)
class X
class Y
class XxY(x: X, y: Y) extends MyProduct(x,y)
Run Code Online (Sandbox Code Playgroud)
我正在尝试检查该MyProduct
特征的论据。更具体地说,我想提取一些信息,例如字符串“x”和“y”,它们指示 的哪些字段XxY
传递给MyProduct
.
重要的是,我需要满足具有相同类型的多个字段的情况,例如class XxYxY(x: X, y1: Y, y2: Y) extends MyProduct3(x, y1, y2)
,因此从类型参数进行推理是不够的。
我想也许问题是我还没有找到一种方法来为条款extends
本身添加符号。我可以找到ClassDef
for XxY
,从中我可以提取parents
并获取已经构造的类型MyProduct[X,Y]
。我还查看了symbol.declarations
封闭模块和XxY.<init>
函数的 ,以查看是否有可用于查找参数的数据,但这些似乎都没有我正在寻找的信息。
查看封闭模块的树让我认为这些信息可能被删除,而是需要从源代码解析为文本,但我希望有人有更好的解决方案。
从评论中编辑:
作为输入,我有一个Type
封闭对象/模块的实例。例如:
trait MyProduct[A, B](a: A, b: B)
class X
class Y
class XxY(x: X, y: Y) extends MyProduct(x,y)
Run Code Online (Sandbox Code Playgroud)
作为输出,我想要一些允许我检查 extends 子句中使用的特征的参数的东西。
我有以下内容case class
:
case class Example[T](
obj: Option[T] | T = None,
)
Run Code Online (Sandbox Code Playgroud)
Example(myObject)
这使我能够像而不是那样构建它Example(Some(myObject))
。
要使用 obj,我需要将其标准化为Option[T]
:
lazy val maybeIn = obj match
case o: Option[T] => o
case o: T => Some(o)
Run Code Online (Sandbox Code Playgroud)
the type test for Option[T] cannot be checked at runtime
我尝试过TypeTest
,但也收到警告 - 或者我发现的解决方案看起来非常复杂 - 请参阅/sf/answers/4872566401/
在Scala 3中是否有更好的方法来实现这种模式?
我想为一个函数定义一个类型,该函数执行某些操作,然后返回另一个相同类型的函数[可以是它本身]。明显的想法不起作用(“非法循环类型引用”错误):
type Behavior[S] = S => Behavior[S]
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么明显的东西吗?我也不明白如何表达“函数返回自身”的想法。
我将 Scala 3 的编译器称为库,它CompilationUnit
在编译后为您提供每个源代码。它有tpdTree
,听起来应该包含类型信息。
我正在尝试遍历树来获取任何类型符号:
atPhase(Phases.typerPhase.next) {
// traverse unit.tpdTree...
}
Run Code Online (Sandbox Code Playgroud)
树行走看起来像:
class ValExtractor(tpes: Set[String]) extends tpd.TreeTraverser:
def isAcceptableType(tpe: Types.Type)(using ctx: Context): Boolean =
tpe.baseClasses.exists { sym =>
tpes.contains(sym.fullName.toString)
}
override def traverse(tree: tpd.Tree)(using ctx: Context): Unit =
tree match
case tpd.ValDef(name, tpt, _) if isAcceptableType(tpt.tpe) =>
println("do something")
case t: tpd.Template => this((), t.body)
case t: tpd.PackageDef => this((), t.stats)
case t: tpd.TypeDef => this((), t.rhs)
case _ => ()
end ValExtractor
Run Code Online (Sandbox Code Playgroud)
我明白了
[info] assertion …
Run Code Online (Sandbox Code Playgroud) 在 Scala 3 中,我可以使用 lambda 类型为状态定义一个函子:
given stateFunctor[S]: Functor[[A] =>> State[S, A]] with
override def map[A, B](a: State[S, A])(fx: A => B): State[S, B] = State(a.run.andThen { case (s, a) => (s, fx(a)) })
Run Code Online (Sandbox Code Playgroud)
我希望它能与?
或_
通配符一起使用:
given stateFunctor[S]: Functor[State[S, ?]] with
override def map[A, B](a: State[S, A])(fx: A => B): State[S, B] = State(a.run.andThen { case (s, a) => (s, fx(a)) })
Run Code Online (Sandbox Code Playgroud)
但我收到以下编译错误:
类型参数domain.State[S, ? <: AnyKind] 与其绑定 [_$1] 的类型不同,给定 stateFunctor[S]: Functor[State[S, ? <: AnyKind]] 与
为什么不起作用?我缺少什么?我认为 …
关于如何在 Scala 3 中实现以下功能有什么想法吗?
我同意inline
与否,一般来说,轻微的语法改变是可以的(即使是宏也可以)。但我不知道如果没有asInstanceOf
.
type Pred[A] = A => Boolean
/** Computes values of predicates and combines them with `&&`.
*
* The implementation does not use `asInstanceOf` or `isInstanceOf` */
inline def tupled[Args <: Tuple](inline preds: Tuple.Map[Args,Pred], inline args: Args): Boolean
Run Code Online (Sandbox Code Playgroud)
例子:
val pred: (Int => Boolean, Int => Boolean) = (_ < 0, _ > 0)
println(tupled[(Int, Int)](pred)( 1, 2)) // should print false
println(tupled[(Int, Int)](pred)(-1, 2)) // should print true
Run Code Online (Sandbox Code Playgroud) scala ×10
scala-3 ×10
sbt ×2
akka ×1
akka-http ×1
akka-stream ×1
dotty ×1
enums ×1
implicit ×1
scala-2.10 ×1
scala-macros ×1
tuples ×1