You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala技术问询:从字符串移除指定元素并通过Trait实现多服务复用

Solution for Your Scala String Manipulation Requirements

Got it, let's tackle your two requirements one by one—first building a reusable string stripping function, then creating a trait to handle those source prefixes across multiple services.

1. Function to Remove All Elements from a List/Map from a String

First, let's cover the utility function that can strip every element in a list (or map keys/values) from a target string. We'll make this flexible to handle both lists and maps:

For List Elements

This function takes a target string and a list of substrings to remove, then iteratively strips each one out:

def stripAllFromList(target: String, toRemove: List[String]): String = {
  toRemove.foldLeft(target) { (current, str) =>
    current.replace(str, "")
  }
}

Example usage:

val sampleStr = "http://localhost:9000/source.address.com/7808/project/repo"
val sourcesToRemove = List("http://localhost:9000/", "source.address.com/7808/")
stripAllFromList(sampleStr, sourcesToRemove) // Returns "project/repo"

For Map Elements

If you need to handle maps (e.g., removing keys or values), we can adjust the function to take a map and choose whether to strip keys, values, or both:

def stripAllFromMap(target: String, toRemoveMap: Map[String, String], stripKeys: Boolean = true, stripValues: Boolean = true): String = {
  val elements = (if (stripKeys) toRemoveMap.keys else Nil) ++ (if (stripValues) toRemoveMap.values else Nil)
  elements.foldLeft(target) { (current, str) =>
    current.replace(str, "")
  }
}

Example usage:

val sourceMap = Map("sourceHost" -> "source.address.com", "buildHost" -> "build.address.com")
stripAllFromMap(sampleStr, sourceMap, stripValues = true) // Removes the host values, leaving "http://localhost:9000//7808/project/repo"

2. Trait for Source Prefix Stripping (Multi-Service Reusable)

Now, let's build a trait that encapsulates the logic to strip those source-related prefixes, with support for adding new sources as needed. The goal is to let different services extend this trait and customize the list of sources they need to handle.

Step 1: Define the Trait

The trait will include an abstract sources method (so implementations can define their own source list) and a concrete stripSourcePrefix method that handles the actual stripping:

trait SourcePrefixStripper {
  // Abstract method: each service can override this to add their own sources
  def sources: Set[String]

  // Concrete method to strip the source prefix from a string
  def stripSourcePrefix(input: String): String = {
    // Find the first source that exists in the input string
    sources.find(input.contains) match {
      case Some(source) =>
        // Split the input at the source, take the part after, then split at the next slash to remove the port number
        val afterSource = input.split(source, 2).last
        // Split on the first slash to remove the port (like 7808/ or 17808/)
        afterSource.split("/", 2).lastOption.getOrElse(afterSource)
      case None =>
        // If no source is found, return the original string
        input
    }
  }
}

Step 2: Implement the Trait for a Service

Each service can extend this trait and define its own set of sources. You can also create a base implementation with common sources, then extend it for services with additional sources:

// Base implementation with common sources
class BaseSourceStripper extends SourcePrefixStripper {
  override def sources: Set[String] = Set("source.address.com", "build.address.com")
}

// Extended implementation for a service that needs an extra source
class ExtendedSourceStripper extends BaseSourceStripper {
  override def sources: Set[String] = super.sources + "test.address.com"
}

Step 3: Usage Example

Let's test this with your sample URLs:

val baseStripper = new BaseSourceStripper()
val sampleUrl1 = "http://localhost:9000/source.address.com/7808/project/repo"
val sampleUrl2 = "http://localhost:9000/build.address.com/17808/project/repo"

baseStripper.stripSourcePrefix(sampleUrl1) // Returns "project/repo"
baseStripper.stripSourcePrefix(sampleUrl2) // Returns "project/repo"

// Test the extended version with a new source
val extendedStripper = new ExtendedSourceStripper()
val sampleUrl3 = "http://localhost:9000/test.address.com/9999/project/repo"
extendedStripper.stripSourcePrefix(sampleUrl3) // Returns "project/repo"

This setup is fully reusable across services—just extend the trait (or the base class) and add any new sources you need.

内容的提问来源于stack exchange,提问作者crowgers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:39:46