English 中文(简体)
Scala: 可否指明采用某种方法的通用类别
原标题:Scala: Is it possible to indicate a generic class which implements a certain method

我认为,用一个简单的例子来解释这一点比较容易。 (帮助重写标题是受欢迎的;-)

我愿采用<条码>,使用<条码>,并使用<条码>简单明了的代号/代码>,自动将其添加到支持<条码>的任何类别中。

它非常容易:

class EnhancedInt(x: Int) { def squared = x * x }

implicit def IntToEnchancedInt(x: Int) = new EnhancedInt(x)

但是,如果存在任何或任何错误,我会发现以下错误:

scala> class EnhanceAny(x: AnyVal) { def squared = x * x }
<console>:7: error: value * is not a member of AnyVal
       class EnhanceAny(x: AnyVal) { def squared = x * x }

我很想知道,我如何能够将其应用于任何数字类别,或甚至适用于支持<代码>*的任何类别。

最佳回答
问题回答

Think about it. Multiplication have different properties on different objects. Integer multiplication, for example, is associative and commutative, scalar multiplication is not commutative. And multiplication on floating point numbers... But, of course, you can have what you want with trait or with "trait and implicit" construction which resembles a typeclass.





相关问题
Generic constraint exclusion

Sorry for asking silly question Is it possible to enforce constraint on generic in such a way that the given T can be derived from any reference Type except some A,B,C (where A,B,C are reference ...

Can a Type Derive from Itself?

When enforcing a Generic constraint class GenericTest { public void Sample<T>(T someValue) where T:Racer,new() { Console.WriteLine(someValue.Car); } } The Type T should be ...

C# Deriving Generic Methods

When i need to pass a Generic Type I can use the Syntax (Example : Ofcourse it is not a Generic Method) public void Sample(T someValue) { ...... } What is the benefit of declaring Sample<T>...

What is the benefit to using List<T> over IEnumerable<T>?

or the other way around? I use generic lists all the time. But I hear occasionally about IEnumerables, too, and I honestly have no clue (today) what they are for and why I should use them. So, at ...

热门标签