小编the*_*res的帖子

Scala短和类型安全的演员操作员

我不喜欢Scala isInstanceOf和asInstanceOf方法 - 它们很长并且asInstanceOf可以抛出异常所以我们需要在几个中使用它.更好的方法是使用模式匹配:Scala:如何转换变量?但对于非常简单的操作,它也可能相对较长.在C#中,我们有'is'和'as'运算符,所以我想在Scala中实现隐式定义.我的代码看起来像这样:

scala> class TypeCast(x:Any){
     | def is[T](t:Class[T]) = t.isInstance(x) 
     | def as[T](t:Class[T]):Option[T] = if(t.isInstance(x)) Option(t.cast(x)) else None
     | }
defined class TypeCast

scala> implicit def TypeCastID(x:Any)=new TypeCast(x)
TypeCastID: (x: Any)TypeCast

scala>  123 as classOf[String]
res14: Option[String] = None

scala> "asd" as classOf[String]
res15: Option[String] = Some(asd)
Run Code Online (Sandbox Code Playgroud)

它有一个优点 - 实现null-object模式但也有缺点:

  • 需要使用classOf [T]运算符 - 它太长了

  • 开销与隐式def连接,用于这种简单的操作

所以没有实际的理由使用它.我想知道有没有办法实现这个而不需要使用classOf [T]?

scala

8
推荐指数
1
解决办法
2597
查看次数

在Scala案例类树中更改节点

假设我使用case类构建了一些树,类似于:

abstract class Tree
case class Branch(b1:Tree,b2:Tree, value:Int) extends Tree
case class Leaf(value:Int) extends Tree
var tree = Branch(Branch(Leaf(1),Leaf(2),3),Branch(Leaf(4), Leaf(5),6))
Run Code Online (Sandbox Code Playgroud)

现在我想构建一个方法来将具有一些id的节点更改为另一个节点.很容易找到这个节点,但我不知道如何改变它.有没有简单的方法呢?

tree scala pattern-matching case-class

5
推荐指数
1
解决办法
1983
查看次数

标签 统计

scala ×2

case-class ×1

pattern-matching ×1

tree ×1