带有关键字使用的 Scala

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6761534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:14:09  来源:igfitidea点击:

Scala with keyword usage

scala

提问by den bardadym

I found simple example:

我找到了一个简单的例子:

class Post extends LongKeyedMapper[Post] with IdPK {
    def getSingleton = Post

    object title extends MappedText(this)
    object text extends MappedText(this)
    object date extends MappedDate(this)
}


object Post extends Post with LongKeyedMetaMapper[Post] {
    def getPosts(startAt: Int, count: Int) = {
        Post.findAll(OrderBy(Post.date, Descending), StartAt(startAt), MaxRows(count))
    }

    def getPostsCount = Post.count
}

What does it mean with IdPK?

这是什么意思with IdPK

Thanks.

谢谢。

回答by Jonas

withmeans that the class is using a Trait via mixin.

with意味着该类正在通过mixin使用 Trait 。

Posthas the Trait IdPK(similar to a Java class can implementsan Interface).

Post具有 Trait IdPK(类似于 Java 类可以implements是接口)。

See also A Tour of Scala: Mixin Class Composition

另请参阅Scala 之旅:Mixin 类组合

回答by Colin Woodbury

While this isn't a direct answer to the original question, it may be useful for future readers. From Wikipedia:

虽然这不是对原始问题的直接回答,但它可能对未来的读者有用。来自维基百科

Scala allows to mix in a trait (creating an anonymous type) when creating a new instance of a class.

Scala 允许在创建类的新实例时混合使用特征(创建匿名类型)。

This means that withis usable outside of the top line of a class definition. Example:

这意味着它with可以在类定义的顶行之外使用。例子:

trait Swim {
  def swim = println("Swimming!")
}

class Person

val p1 = new Person  // A Person who can't swim
val p2 = new Person with Swim  // A Person who can swim

p2here has the method swimavailable to it, while p1does not. The realtype of p2is an "anonymous" one, namely Person with Swim. In fact, withsyntax can be used in any type signature:

p2这里有swim可用的方法,而p1没有。的真实类型p2是“匿名”类型,即Person with Swim. 事实上,with语法可用于任何类型签名:

def swimThemAll(ps: Seq[Person with Swim]): Unit = {
  ps.foreach(_.swim)
}

EDIT (2016 Oct 12):We've discovered a quirk. The following won't compile:

编辑(2016 年 10 月 12 日):我们发现了一个怪癖。以下不会编译:

 // each `x` has no swim method
 def swim(xs: Seq[_ >: Person with Swim]): Unit = {
   xs.foreach(_.swim)
 }

Meaning that in terms of lexical precedence, withbinds eagerly. It's _ >: (Person with Swim), not (_ >: Person) with Swim.

这意味着就词汇优先级而言,with热切地绑定。是_ >: (Person with Swim),不是(_ >: Person) with Swim