簡體   English   中英

Scala中的字符串伴侶對象

[英]String companion object in scala

給定一個具有“轉換器”的類型,我想使用該類型的伴隨對象對方法調用進行自動轉換。 也就是說,根據以下定義,

case class Converted(name: String)

trait Converter[A] {
  def perform: Converted
}

implicit val StringConverter = new Converter[String] {
  def perform = Converted("String")
}

使以下代碼起作用:

implicit def toConverter(a: String.type): Converted = 
  implicitly[Converter[String]].perform // Error: `Found String.type, required AnyRef`

def f(needsConverted: Converted) = ???

f(String) // <- That's what I would like to be able to write.

但這失敗了,並且兩次轉換嘗試都失敗了。 請注意,我無法更改f因為它是由第三方庫提供的,並且其中有很多。

  1. 我可以使用隱式編譯f(String)嗎?

如果對於字符串來說不可能,那么確實有伴隨對象的類又該如何呢?

object TheClass

case class TheClass()

implicit val TheClassConverter = new Converter[TheClass] {
  def perform = Converted("TheClass")
}

implicit def toConverter[A: Converter](a: A.type): Converted =
  implicitly[Converter[A]].perform // Error: `Not found value A`

implicit def toConverter(a: TheClass.type): Converted = 
  implicitly[Converter[TheClass]].perform // This works but is not generic

f(TheClass) // This works.
  1. 我可以制作第一個toConverter進行編譯嗎?

我可以使用隱式編譯f(String)嗎?

不會。您可以定義一個名為String的值,但它不會與String類型有關。

 implicit toConverter[A: Converter](a: A.type): Converted = implicitly[Converter[A]].perform 

A.type A必須是一個 它與類型參數A不相關。

實際上,就Scala的類型系統而言,類/特征與其伴隨對象之間沒有關系。 因此,您無法做一般的事情。

當然,如果您不堅持使用()而不是[] ,那么它將變得無關緊要:

def f1[A: Converter] = f(implicitly[Converter[A]].perform)

f1[String]
f1[TheClass]

可以為伴隨類型MyClass.type定義隱式實例,而不是為MyClass類型定義隱式實例。

implicit val TheClassConverter: Converter[MyClass.type] = new Converted[MyClass.type] {
  def perform = Converted("MyClass")
}

不確定,您要完成什么,但以下對我有用

case class Converted(name: String)

trait Converter[A] {
  def perform: Converted
}

implicit def toConverted(name: String) = Converted("String")
implicit def toIntConverted(int: Int) = Converted("Int")

def f(needsConverted: Converted): String = needsConverted.name

f("some")
f(5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM